createContext is a React function that defines a context object for sharing a value with descendant components. Store the context outside components so multiple components can reference it. section 10.1.1 section 10.1.3
Use the context object with its provider and consumers:
- Call createContext(defaultValue); the argument becomes the fallback value when no associated provider exists. section 10.1.3
- Wrap the relevant component tree in Context.Provider and pass the current value through its value property. section 11.4.2
- Read the nearest provided value with useContext(Context); consumers can also use Context.Consumer with a render prop. section 10.1.3
Sharing a dashboard name
import { createContext, useContext } from "react"; const NameContext = createContext(); function UserButton() { const name = useContext(NameContext); return <button>👤 {name}</button>; } function Dashboard() { return ( <NameContext.Provider value="Ada"> <UserButton /> </NameContext.Provider> ); } section 10.1.1
Listing 10.2 Dashboard with context
import { createContext, useContext } from "react"; #1
const BUTTON_STYLE = {
display: "inline-block",
padding: "4px 10px",
background: "transparent",
border: "0",
};
const HEADER_STYLE = {
display: "flex",
justifyContent: "flex-end",
borderBottom: "1px solid",
};
const NameContext = createContext(); #2
function Button({ children }) {
return <button style={BUTTON_STYLE}>{children}</button>;
}
function UserButton() { #3
const name = useContext(NameContext); #4
return <Button>👤 {name}</Button>;
}
function Header() { #3
return (
<header style={HEADER_STYLE}>
<Button>Home</Button>
<Button>Groups</Button>
<Button>Profile</Button>
<UserButton />
</header>
);
}
function Welcome() { #3
const name = useContext(NameContext); #4
return (
<section>
<h1>Welcome, {name}!</h1>
</section>
);
}
function Main() { #3
return (
<main>
<Welcome />
</main>
);
}
function Dashboard({ name }) {
return (
<NameContext.Provider value={name}> #5
<Header />
<Main />
</NameContext.Provider>
);
}
function App() {
return <Dashboard name="Alice" />; #6
}
export default App;
Browse the complete dashboard listing showing createContext, useContext, and the component tree that consumes the shared value. section 10.1.1

