Suppose a menu needs the same links in several components. Passing those links through components that do not use them is prop drilling. React Context lets a provider supply the links to descendants that need them; useContext reads that value. section 10.6 section 11.4.2
Share menu links
Define a context where components can import it: `const MenuContext = createContext([]);`. Wrap the relevant components with `<MenuContext.Provider value={links}>...</MenuContext.Provider>`. Inside a descendant, read the links with `const links = useContext(MenuContext);`. Import `createContext` and `useContext` from `react`. section 11.4.2
useContext takes a context created with createContext and returns the value from the nearest matching provider above the component. If there is no such provider, it returns the default passed to createContext—an empty link list in this example—rather than throwing an error. section 10.1.1 section 10.5 section 11.4.2
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;
See a dashboard where UserButton reads a name from context instead of receiving it through intervening components. section 10.1.1
Use useState for local component state; useContext instead reads a value supplied elsewhere in the component tree. For functional components, useContext is recommended over the context’s `.Consumer` alternative. section 7.1.4 section 10.6

