This React hook helps you identify what caused an update or re-render in your React component tree
Install the useWhyUpdate
package with yarn or npm.
yarn add @modus/react-whyupdate
// or
npm install @modus/react-whyupdate
import React from 'react';
import useWhyUpdate from '@modus/react-useWhyUpdate';
const MyComponent = props => {
useWhyUpdate(props);
return <div>`Hello ${props.name}!`</div>;
};
Watch the console for information of why the component updated.
You also can pass select properties to the hook.
const MyComponent = ({ name, greeting }) => {
useWhyUpdate({ name });
return (
<div>
`${greeting} ${name}!`
</div>
);
};
In this example we'll get notified about changes in the name
prop, only.
const MyComponent = ({ name, greeting }) => {
const [count, setCount] = useState(1);
useWhyUpdate({ name }, { count });
return (
<div>
`${greeting} ${name} ${count} times!`
</div>
);
};
Notice how we separated state from props via another argument. While you could keep all values in a single object, we find it easier to read and maintain if state and prop objects are clearly decoupled.
Note: You can pass any number of arguments to the hook, as long as they are objects.
Your project should already be running React 16.8+ (hooks required).
This library is incredibly small (just 202 bytes compressed), but we still make sure it's removed from production build. It only runs when NODE_ENV !== "production"
.
This project uses Jest for unit testing. To execute tests run this command:
yarn test
It's useful to run tests in watch mode when developing for incremental updates.
yarn test:watch
Modus Create is a digital product consultancy. We use a distributed team of the best talent in the world to offer a full suite of digital product design-build services; ranging from consumer facing apps, to digital migration, to agile development training, and business transformation.
This project is part of Modus Labs.
This project is MIT licensed.