Search code examples
reactjsreact-context

When a React context state updates does it force a rerender of the child components if its context is not being used?


Just asking before I actually dive into this as this will rewrite a bunch of navigation logic.

Can I have the following structure where I have a list screen and an edit screen as follows

<DataProvider>
  <Navigator>
    <Screen name="list" component={ComponentThatUseData} />
    <Screen name="list different layout" component={ComponentThatUseData} />
    <Screen name="list another different layout" component={ComponentThatUseData} />
    <Screen name="edit" component={ComponentThatDoesNotUseData}>
  </Navigator>
</DataProvider>

If DataProvider has a useState and I update that will it cause a re-rendeer of the edit screen even though the useContext is not invoked? Since a re-render will cause my edit form to lose focus.


Solution

  • Yes, based on what I understand on the React Documentation, one of the caveats of React Context is that when the state in the Context is updated, the children will be affected, I think it's because the Context Provider is still a React Component.

    React Context Caveat - Section