The React Context hell

Alfredo Salzillo
2 min readApr 25, 2021

What is the React Context hell?

Like the callback hell, usual when jQuery was used for everything, the React Context hell is the nasty code you get taking advantage of the React Context API.

How to fix it?

To clean up the nasty code you get from taking advantage of React Context API we need a way to nest multiple Context.Provider without passing them as children of each other.

To achieve that we can use the React.cloneElement API.

The cloneElement API

Clone and return a new React element using element as the starting point. The resulting element will have the original element’s props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

We can use the cloneElement API to reduce a collection of providers, this way we don't have to nest them inside each other.

The last element of the array is the content of the app.

Using reduceRight we preserve the nesting to make the HelloWorld element a child of all the providers.

To make it simpler to use we can implement a MultiProvider component.

Now we can refactor the example using the MultiProvider.

You can find an implementation of MultiProvider inside the react-pendulum library.

--

--