Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React re-render all components when any state changes within context consumers?

Tags:

reactjs

I'm building an app where I started moving a lot of props I was passing all over the place into context. Essentially I have a context provider component wrapping many children components.

Since I did this I'm having trouble with re-renders. More specifically, I have a graph in one component that is re-rendering when there is a state change in a sibling component that should have no impact on the graph (not passed in as a prop or shared context variable).

Is this expected behavior? And if it is, then should I try to "localize" context as much as possible?

like image 872
userNick Avatar asked Oct 25 '25 03:10

userNick


1 Answers

The default behavior is that when a component renders, its children render too. This in turn will cause the grandchildren to render, and so on.

You can skip rendering a component by using PureComponent / shouldComponentUpdate (in class components) or React.memo (in function components). These techniques let you specify that if props didn't change, then the component does not need to render again. If rendering is skipped, then the tree below the component will also be skipped, with one caveat: components that consume the context will rerender if the context value changed, even if their immediate parent did not render.

It's often good to put one of these render-blocking components as an immediate child of your context provider. That way, if the only thing you change is the context value, then the only components that will rerender are ones that are explicitly consuming the context.

like image 117
Nicholas Tower Avatar answered Oct 26 '25 18:10

Nicholas Tower