• Stars
    star
    612
  • Rank 70,983 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A React hook and an easy to use babel-pugin to debug various React official hooks

use-what-changed

A tool and utility to debug major React hooks

Better than console logs and debugger

Don't believe. Try this codesandbox

React | React native | React with Electron


Debug following hooks

useEffect | useCallback | useMemo | useLayoutEffect | Custom hooks using core hooks

Working Example

Open the codesandbox link and see the console. You can uncomment the other hooks, and see the console accordingly, when the value changes across rerenders.

codesandbox use-what-changed example

Install

If you use yarn. Run

yarn add @simbathesailor/use-what-changed --dev

If you use npm. Run


npm i @simbathesailor/use-what-changed --save-dev

Motivation

I have been working on hooks for quite a long time. I use react hooks every day in my open source projects and also at work.

Now, using useEffect, useCallback, useMemo have really helped me compose the logic well together. But when the dependency list gets long. When I say long , it can be any thing greater than 3 for me and can be more or less for others.

With these large dependency array, I found it really difficult to debug and find out what is causing my useEffect to run again( same for useCallback and useMemo). I know two strategies to debug:

  1. Break the useEffect logic into multiple useEffect. It is still fine, but expertise and time constraints will be there. People will not break the useEffect logic into smaller pieces first, they will try to spend time using logging the values and adding debugger so that not to change the production code.
  1. Make use of usePrevious hook which can be defined something like this
import React from 'react';

function usePrevious(value) {
  const ref = React.useRef(value);

  React.useEffect(() => {
    ref.current = value;
  });

  return ref.current;
}

export default usePrevious;

And can be consumed like this:

const previousA = usePrevious(a);

const previousB = usePrevious(b);

const previousC = usePrevious(c);

useEffect(() => {
  if (previousA !== a) {
    console.log(`a has changed from ${previousA} to ${a}`);
  }

  if (previousB !== b) {
    console.log(`a has changed from ${previousB} to ${b}`);
  }

  if (previousC !== c) {
    console.log(`a has changed from ${previousC} to ${c}`);
  }
}, [a, b, c]);

However we can do it , it quite too much of work every time you run in the issue , where useEffect callback is running unexpectedly.

  1. You are coming to an unknown code base, This plugin can really enhance your developer experience when working with hooks. It can give you a strong confidence while you make changes to existing hooks.

Even if you are coming to your own code after days. It becomes very difficult to wrap you head around various multiple hooks . This library with babel plugin helps you to undersrtand it wiothout severe cognitive thinking

  1. It can help beginners to learn react hooks easily. The beginners can reason about their changes easily and also avoid unintended runs of hooks. Hopefully this hook can save a lot of frustation for newcomers.

To solve all the above problems, I tried to create something which can enhance developer experience. Let's see how I tried to solve the problem.

Usage with babel plugin (Recommended)

The package can also be used with a babel plugin which make it more easy to debug.

  1. Run
npm i @simbathesailor/use-what-changed --save-dev
  1. Run
npm i @simbathesailor/babel-plugin-use-what-changed --save-dev

Add the plugin entry to your babel configurations

{
  "plugins": [
    [
      "@simbathesailor/babel-plugin-use-what-changed",
      {
        "active": process.env.NODE_ENV === "development" // boolean
      }
    ]
  ]
}

Make sure the comments are enabled for your development build. As the plugin is solely dependent on the comments.

Now to debug a useEffect, useMemo or useCallback. You can do something like this:

Debug individual hooks

// uwc-debug
React.useEffect(() => {
  // console.log("some thing changed , need to figure out")
}, [a, b, c, d]);

// uwc-debug
const d = React.useCallback(() => {
  // console.log("some thing changed , need to figure out")
}, [a, b, d]);

// uwc-debug
const d = React.useMemo(() => {
  // console.log("some thing changed , need to figure out")
}, [a]);

// uwc-debug
const d = React.useLayoutEffect(() => {
  // console.log("some thing changed , need to figure out")
}, [a]);

Notice the comments uwc-debug in above examples. The comment uwc-debug is responsible for the all the magic.

Debug complete file or line below it.

Notice the comments uwc-debug-below below examples.

React.useEffect(() => {
  // console.log("some thing changed , need to figure out")
}, [a, b, c, d]);

// this comment enables tracking all the hooks below this line. so in this case useCallback and useMemo will be tracked.
// uwc-debug-below
const d = React.useCallback(() => {
  // console.log("some thing changed , need to figure out")
}, [a, b, d]);

const d = React.useMemo(() => {
  // console.log("some thing changed , need to figure out")
}, [a]);

So the example will debug all the hooks below line containing // uwc-debug-below.

No need to add any import for use-what-changed. just add a comment uwc-debug or uwc-debug-below above your hooks and you should start seeing use-what-changed debug consoles. No more back and forth across files and browser, adding debuggers and consoles.

This plugin provides following information :

1. Hook name which it is debugging.

2. File name where hook is written

3. Name of dependencies passed to hook.

4. what has changed in dependency array which caused the re-run of hook with symbol icons ( βœ…, ⏺).

5. Tells you old value and new value of all the dependencies.

6. Tells you whether it is a first run or an update. I found it very helpful in debugging cases.

7. Unique color coding and id for individual hooks for easy inspection

Note: Frankly speaking the whole package was built, cause I was facing problems with hooks and debugging it was eating up a lot of my time. Definitely using this custom hook with babel plugin have saved me a lot of time and also understand unknown edge cases while using hooks


Usage without babel plugin

  1. When only dependency are passed as the single argument
import {
  useWhatChanged,
  setUseWhatChange,
} from '@simbathesailor/use-what-changed';

// Only Once in your app you can set whether to enable hooks tracking or not.
// In CRA(create-react-app) e.g. this can be done in src/index.js

setUseWhatChange(process.env.NODE_ENV === 'development');

// This way the tracking will only happen in devlopment mode and will not
// happen in non-devlopment mode

function App() {
  const [a, setA] = React.useState(0);

  const [b, setB] = React.useState(0);

  const [c, setC] = React.useState(0);

  const [d, setD] = React.useState(0);

  // Just place the useWhatChanged hook call with dependency before your

  // useEffect, useCallback or useMemo

  useWhatChanged([a, b, c, d]); // debugs the below useEffect

  React.useEffect(() => {
    // console.log("some thing changed , need to figure out")
  }, [a, b, c, d]);

  return <div className="container">Your app jsx</div>;
}

Above snapshot show the console log when b and c has changed in the above code example.

  1. Pass two arguments to useWhatChanged which makes it possible for useWhatChanged to log the names of the variables also.
useWhatChanged([a, b, c, d], 'a, b, c, d', 'anysuffix-string'); // debugs the below useEffect

Color coding

A unique background color will be given to each title text. It helps us in recognising the specific effect when debugging. A unique id is also given to help the debugging further.

Demo link

Demo link

Codesandbox link

Medium article link

Electron example

As this lbrary is just javascript and react. It can be used whereever Reactjs exists.

I have included the setup for elctron app with a repo example.

Todos: Need to add an example for react-native, which is work in progress. I will update it in a couple of days.

Electron repo link

Nextjs Example

Nextjs Example

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

simbathesailor

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Contributors

Thanks goes to these wonderful people (emoji key):

Anil kumar chaudhary
Anil kumar Chaudhary

πŸ’» πŸ€” 🎨 πŸ“– πŸ›

More Repositories

1

use-effect-x

🌟 useEffectX 🌟 : An alternative and drop-in replacement for useEffect which provide previous values of dependency items out of the box.
TypeScript
15
star
2

react-infinite-scroll

A dead simple infinite scroll (1.3 kb gzipped) for friends
TypeScript
14
star
3

babel-plugin-use-what-changed

A simple plugin to debug reactjs hooks in react based applications (web, native)
TypeScript
13
star
4

react-image-zoom-hook

A customisable Reactjs hook for image zoom 🌽
TypeScript
8
star
5

envvarprep-loader

A webpack loader which prepares the builds to allow env injection later on without building everything again.
TypeScript
5
star
6

nodejs-express-server

A nodejs repo for learning and experimenting everything in nodejs, setup from scratch
TypeScript
2
star
7

secret-saviour

A private tab manager, hide your private tabs before you go to meeting
JavaScript
2
star
8

github-most-wanted

A Simple app that use GitHub API to list top 10 forked Repositories and top 10 starred Repositories.It auto refreshes in some interval to get the latest list πŸš”
JavaScript
2
star
9

tab-manager

A experimental tab manager
JavaScript
1
star
10

react-key-collector

A small library allows to handle multiple key stroke events in react πŸ”‘
JavaScript
1
star
11

server-side-reactjs

JavaScript
1
star
12

gzippalo

A small nodejs library on top of zlib to allow gzipping set of files.
TypeScript
1
star
13

simbathesailor

My Personal README
1
star
14

react-hooks-patterns-talk

A sample project for presentation
JavaScript
1
star
15

webpack-learner

All the webpack experiments in this repositories
JavaScript
1
star
16

consume-random-number-lib

A sample repo consuming the private github repo
JavaScript
1
star
17

react-playground

A react playground to understand the internals and new APIS which are not released yet.
JavaScript
1
star
18

nextjs-uwc

A nextjs repository showcasing the usage of use-what-changed
JavaScript
1
star
19

shopping-cart-pwa

A simple shopping result pages , shopping cart and checkout page πŸ‘œ 🍹 πŸ‘’
JavaScript
1
star
20

backend-websockets-learn

A sample repository to learn websockets
JavaScript
1
star
21

simbathesailor.dev.new

simbathesailor.dev.new
JavaScript
1
star
22

kalakari-playground

A test bed for using kalakari a component library
JavaScript
1
star
23

push-subscription-server

A node js server sending push subscription πŸ‘½ πŸ“Œ
CSS
1
star
24

gatsby-contentful-blog

A gatsby contentful blog
JavaScript
1
star
25

react-qr-scan

A Reactjs based qrcode scan utility based on html5-qrcode by mejbas
TypeScript
1
star
26

use-intersection-observer

An intersection observer hook for all your purposes
TypeScript
1
star
27

react-native-babel-plugin-example

react-native-babel-plugin-example
Java
1
star
28

react-native-base

A react-native base for all app projects
Java
1
star
29

separate-env-injection-playground

A setup to try to segregate the ENV injection and build process of webpack build of react App
JavaScript
1
star
30

simbathesailor.dev

My Personal website where I write intersection with life, computers and myself
JavaScript
1
star
31

minimal-react-toast

A minimal react toast hook
TypeScript
1
star
32

Dynamic_weather_reporter

This weather application displays current weather and changes background accordingly.It provides temperature in Celsius and Fahrenheit,wind direction in knots and respective cloud icons.This application uses "openweathermap" API.(http://openweathermap.org/)
JavaScript
1
star
33

frontend-websockets-learn

A frontend repo for learning websockets
JavaScript
1
star