Skip to content
Advertisement

React: How to use multiple Contexts of the same type while allowing children to read data from all of them

I have a certain Context setup similar to this

JavaScript

And child components that use it like this

JavaScript

Now I need to do this

JavaScript

Need to provide all parent context’s data of one single Context definition to a set of children

I know useContext can only read the closest parent of a given ContextType, so I’m not sure of how to proceed with this.

Advertisement

Answer

You can’t use two context providers of the same type and have children receive from both. The Context API is such that children components receive the context value from the closest context provider to them in the React tree.

You can, however, use a single provider that instead returns the getData function. Here’s an example using a single DataProvider and a custom React hook to provide the “id” value.

Data.Context.js

JavaScript

index.js

JavaScript

Child component

JavaScript

Edit react-how-to-use-multiple-contexts-of-the-same-type-while-allowing-children-to

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement