Usage of Multiple Contexts

Learn how to nest multiple Providers of the same and different Context type inside of each other.

Nesting multiple Context Providers

It is entirely possible to use multiple Context Providers within the same component hierarchy. Nesting them is not a problem. Even Providers of the same Context type can be nested inside of each other. The Context value of the above Provider is given to the Consumer components:

<MyContext.Provider value="1">
  <MyContext.Provider value="2">
    <MyContext.Consumer>
      {(value) => <p>The value is {value}</p>}
    </MyContext.Consumer>
  </MyContext.Provider>
</MyContext.Provider>

Code example

The above example is completely valid. See the output for yourself by running the code snippet below.

Get hands-on with 1200+ tech skills courses.