Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 everything in the Router component re-renders on every route change

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?

like image 957
jhummel Avatar asked Jun 05 '18 15:06

jhummel


People also ask

How do I stop Rerendering the react?

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.

Why does react keep Rerendering?

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.

How do you find out why a component 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.

Does react router Rerender?

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.


1 Answers

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.

like image 136
AKX Avatar answered Sep 25 '22 04:09

AKX