reactjsredux

Trace why a React component is re-rendering


Is there a systematic approach to debug what is causing a component to re-render in React? I put a simple console.log() to see how many time it renders, but am having trouble figuring out what is causing the component to render multiple times i.e (4 times) in my case. Is there a tool that exists that shows a timeline and/or all components tree renders and order?


Solution

  • You can check the reason for a component's (re)render with the React Devtools profiler tool. No changing of code necessary. See the react team's blog post Introducing the React Profiler.

    First, go to settings cog > profiler, and select "Record why each component rendered"

    React Dev Tools > Settings

    Screenshot of React Devtools profiler

    Note that often the text under "Why did this render?" will just say "Hook(s) n changed", with n being a number.

    To find out which hook this refers to, select the component in the "Components" tab of the React Developer Tools. Then the details area to the right will list all the component's hooks, along with their number and their current state, if any.