I'm trying to understand better why all my components are re-rendering whenever a route changes in React Router v5. Note, these components are only re-rendering not re-mounting. When I open up the react extension in dev tools and select the Highlight Updates
checkbox, I can see all my components get outlined when changing routes, even the components that are at a higher level than the route match:
<Router>
<MyHeader />
<ComponentWithRoutes />
</Router>
In this simple example, I would expect, that changing routes would not re-render the MyHeader
component, since nothing changes. However I will still see a highlight with the dev tools. I assume this is expected, since all the examples in the Docs exhibit the same behavior.
My question is two-fold. 1) What is the actual cause of making a component like MyHeader
to re-render? It doesn't seem like any props or state are changing. Is it because of the way the Router is using the Context API? The Router is rendering and causing the children to re-render? 2) Why isn't this considered wasteful? It seems like even though the actual DOM isn't changing, React would still have to go through the reconciliation steps in the virtual DOM. Is it just so fast it's doesn't matter? What happens when you start having tons of nested components?
But, if we use the useMemo() Hook, we can avoid component re-rendering if the inputs are the same and save the result in the cache. Now, the computed result is stored in the cachedValue variable and useMemo() Hook will return it each time unless the inputs are changed.
In React, every state variable is attached to a particular component instance. In this example, we have a single piece of state, count , which is associated with the Counter component. Whenever this state changes, Counter re-renders.
Using React DevTools to highlight what components rerendered To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.
React components re-render on their own whenever there are some changes in their props or state. Simply updating the state, from a random place in the code, causes the User Interface (UI) elements that get re-rendered automatically.
Yup, this is the lay of the land.
Your components will re-render unless they're React.PureComponent
, or otherwise define shouldComponentUpdate()
, when the parent component is re-rendered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With