Optimizing Provider Context Usage in React
Unleash the Power of Provider Context: Elevating Your React Applications with Expert Strategies
Provider Context solves the problem of
prop-drilling. They provide a cleaner and elegant way to access parent props and setter function in deeply nested children without have to pass them separately through our the chain.
However, they also bring extra re-render to it’s subsequent child.
Let’s understand this by an example.
It is clearly visible that even though we aren’t consuming any context info in our child component, but any change in deeper level causing a re-render.
This is not a bug, this is how react works, if Parent state changes all children re-renders.
We can prevent it by two ways.
Solution 1: Wrapping our Child Component in React.memo()
Note that, wrapping only subsequent component in
React.memo will prevent the re-render, we don’t have to wrap other nested component in
Parent (Only this needs to wraped in React.memo())
GrandGrandChild (Changes Context)
// If there is any other reason other than preventing re-render by Context-Provider
// then all other component may be wraped in React.memo()
Solution 2: Passing the Component tree in Provider via prop
Simply Create a separate for function for Provider and pass components inside it as children.
This utilizes the react concept, if prop doesn’t change do not re-render.
No React.memo() is required.
Here is the code-sandbox link for the above examples:
Thanks for Reading.