3

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?

userNick
  • 503
  • 4
  • 7
  • 25

1 Answers1

5

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.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • 1
    Thanks! Just wrapping my graph component's export in `memo` solved my immediate problem. I think I would expect, and want the components that consume specific context values to re-render when changed. – userNick Jul 31 '20 at 02:34