Tracking useless re-renders examples, using
It's enabled by default (only during development).
Let's take the below example with the
This component uses the
You may have noticed (if you've cloned NRN locally and played around) that there are a few warnings regarding
ReactAsyncHighlighter being re-rendered with
Re-rendered although props and state objects are the same. warning.
This warning is generated by
why-did-you-render and tells us something is wrong with the
Unfortunately, because it's a nested dependency, it's quite hard for us to do anything to fix that, we can't do much rather than telling the maintainers about the issue.
What we can do, is to see how
why-did-you-render can help us with our own
Clicking on the button above will generate a warning in the browser console (development env only)
But, the below code wouldn't generate a warning
The answer is simple, it's because codeBlockStyle takes an object as property, and this object is being redefined every time with a new reference.
Because the reference between the old render and the new render is different, React shallow comparison believes it's a different value, even though the value is actually the same.
This kind of mistakes are caught by
why-did-you-renderand are visible in the console, so that it's easier to notice, and fix.
In the above case, what can be done to avoid such issue is to define the
codeBlockStylevalue before (using
const codeBlockStyle = ...) so that the reference won't change.
And guess why we took this example?
Exactly, we actually made that exact mistake when writing NRN demo, and we thought that'd be a great example. (^_^)'