• Accueil
  • Exemples
    Native features
    SSR (getServerSideProps)SSGSSG using fallbackSSG using revalidateCatch-all routes
    Built-in features
    HostingStages & secretsCI/CDStatic i18nMonitoringAPI (Airtable)CSS-in-JSCookies consentAnalyticsIconsCSS AnimationsUI components libraryDocs siteMarkdown as JSX
    Built-in utilities
    I18nLink componentAirtableAsset componentHooksHOCsAPIErrors handlingBundle analysisSVG to ReactSecurity auditTracking useless re-renders
  • Documentation
  • Code source
  • Aller au CMS

Built-in utilities

  • I18nLink component
  • AirtableAsset component
  • Hooks
  • HOCs
  • API
  • Errors handling
  • Bundle analysis
  • SVG to React
  • Security audit
  • Tracking useless re-renders

Previous section - Accueil

Tracking useless re-renders examples, using why-did-you-render

why-did-you-render is a library that's built-in and will warn you about useless React re-renderings.
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 />
Why is that?
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. (^_^)'

Utilisateur 1 - 2023
Tous droits réservés

Conditions générales d'utilisation
Politique de confidentialité
/static/images/LOGO_Powered_by_UNLY_BLACK_BLUE.svg