Mario Brusarosco

react context

In the ground since Fri Oct 01 2021

Last watered inFri Oct 01 2021

Related Topics

React Context

Understanding Nested Contexts and Hierarchy

When you have nested contexts, the innermost context takes precedence over the outer context. This means that the innermost context will be used when a component consumes multiple contexts.

On the example below the ChildComponent doesn't have its own context, so it uses the context provided by the ParentComponent. So the value is light. If, we didn't have ParentComponent with a Context, only then, the Context's default value would be used: light.

1import * as React from "react";
2
3const ParentComponent = () => {
4 return (
5 <themeContext.Provider value="dark">
6 <ChildComponent />
7 </themeContext.Provider>
8 );
9};
10
11const ChildComponent = () => {
12 const theme = React.useContext(themeContext);
13
14 return <div>Theme is {theme}</div>;
15};