Optimizing Provider Context Usage in React

Unleash the Power of Provider Context: Elevating Your React Applications with Expert Strategies

Photo by Rahul Mishra on Unsplash

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.

Check the consoles.

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 memo un-necessarily.

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()
In Above example modify the Child Component to use React.memo()
Only GrandChild is getting Re-rendered

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.

Prevent extra re-render by creating separate component
No Extra re-render.

Here is the code-sandbox link for the above examples:

Thanks for Reading.