Currently I have four contexts that wrap all my routes (as shown bellow) so that I don’t have lost providers all around my app screens and components. As far as I know, when I modify the value of a context variable, every component that uses it will update too, what can lead to memory problems, but my question is: if my providers, that wrap all routes/screens, even the ones that uses no context variable, may cause the same memory related problems.
<AuthProvider> <SelectedBranchProvider> <SelectedEventProvider> <DrawerFormProvider> <RightDrawerNavigator /> </DrawerFormProvider> </SelectedEventProvider> </SelectedBranchProvider> </AuthProvider>
Advertisement
Answer
The danger with context isn’t memory issues, it’s unneeded re-renders. The way Context is implemented defeats some of React’s diffing, so a change in Context can cause a re-render in any component that uses the same Context, even if the value that changes is unused in the component.
If you have a small app, or only rarely change what’s in your context, you’ll probably never hit these limitations. Good use cases for context are things that would require many re-renders and rarely change, like user language or app theme.
The docs for Context have a caveats section that goes over this: https://reactjs.org/docs/context.html#caveats
Here’s a blog post with a good example of how this can cause re-renders: https://blog.logrocket.com/pitfalls-of-overusing-react-context/