Tracking useless re-renders examples, using why-did-you-render
It's enabled by default (only during development).
Let's take the below example with the Code
component.
This component uses the CodeBlock
and ReactAsyncHighlighter
components.
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 ReactAsyncHighlighter
component.
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 Code
component.
Clicking on the button above will generate a warning in the browser console (development env only)
1
2
3
4
5
6
7
8
<Code
codeBlockStyle={{
margin: 0,
textAlign: 'left',
}}
/>
But, the below code wouldn't generate a warning
1
2
3
<Code />
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-render
and 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
codeBlockStyle
value 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. (^_^)'