Skip to content

React Hook for identifying why a component re-rendered

License

Notifications You must be signed in to change notification settings

moduslabs/react-whyupdate

Repository files navigation

useWhyUpdate: Identify Why a React Component Re-rendered

MIT Licensed Powered by Modus_Create

This React hook helps you identify what caused an update or re-render in your React component tree

Getting started

Install the useWhyUpdate package with yarn or npm.

yarn add @modus/react-whyupdate

// or

npm install @modus/react-whyupdate

Usage

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.

Destructured props

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.

Watching state

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.

Dependencies

Your project should already be running React 16.8+ (hooks required).

Running in production

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".

Development

Testing

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

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.

Modus Create

This project is part of Modus Labs.

Modus Labs

Licensing

This project is MIT licensed.

About

React Hook for identifying why a component re-rendered

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published