Track Redundant React Hooks Re-Renders With “Why Did You Render” Version 3

@welldone-software/why-did-you-render version 3 is released with many features, including tracking of React hooks issues.

Vitali Zaidman
Apr 5 · 2 min read

Sometimes you know a certain React component is costly to re-render and sould not be re-rendered unless there’s a good reason for it to re-render.
But how can you enforce it?

If a re-render is caused by state, props, this.forceUpdate(), or by the component’s father render, the library will notify you. You can read about it in the first article.

In this part we would discuss how a React hook can cause a component to be re-rendered and how to detect if this re-render can be prevented using the @welldone-software/why-did-you-render library.

The main thing to know about hooks is that if you set any hook’s state to be the same as it’s previous state, it would not cause a re-render. If the state is different, even if it deep equals to the previous one, it would cause a re-render.

The useState Hook

In the following sandbox, we show how setState hooks may cause a redundant re-render:

If the component is tracked by whyDidYouRender, and you set it’s state to be the same by value but not by reference, you’ll receive the following notification in the console:

To fix this, do not call setHookState if the state you pass to it is deeply equal to the previous state.

For example in our case the following code could help:

You can also create a custom hook to achieve this:

The useReducer Hook

The same principle as discussed in the useState hook, applies to the useReducer hook.

Make sure the state returned from the reducer is not a different object that equals by value but different by reference from the previous state:

Here is an example:

Other React hooks

The same principle applies to all the other hooks.

Custom Hooks

Would be tracked by tracking the custom hooks.

Welldone Software

The leading full-stack consultancy. Creating amazing frontends and rock-solid backends using top notch technologies and practices. Visit us at https://welldone.software.

Vitali Zaidman

Written by

https://twitter.com/vzaidman ⎝(•ω•)⎠ https://vzaidman.com

Welldone Software

The leading full-stack consultancy. Creating amazing frontends and rock-solid backends using top notch technologies and practices. Visit us at https://welldone.software.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade