Nested context places one React Context provider inside another provider or provider subtree. A consumer reads the nearest provider above it; without one, it receives the context’s default value. section 10.1.3
Button borders in a shop
A shop can use a default 1-pixel border for buttons, override the footer with 2 pixels, and wrap each cart button in a provider with value 5. Each Button reads BorderContext, so the nearest provider determines its border width. section 10.1.3
Listing 10.4 Border width by context
import { useContext, createContext } from "react";
const BorderContext = createContext(1); #1
function Button({ children }) {
const borderWidth = useContext(BorderContext); #2
const style = {
border: `${borderWidth}px solid black`,
background: "transparent",
};
return <button style={style}>{children}</button>;
}
function CartButton() {
return (
<BorderContext.Provider value={5}> #3
<Button>Cart</Button>
</BorderContext.Provider>
);
}
function Header() {
const style = {
padding: "5px",
borderBottom: "1px solid black",
marginBottom: "10px",
display: "flex",
gap: "5px",
justifyContent: "flex-end",
};
return (
<header style={style}>
<Button>Clothes</Button>
<Button>Toys</Button>
<CartButton />
</header>
);
}
function Footer() {
const style = {
padding: "5px",
borderTop: "1px solid black",
marginTop: "10px",
display: "flex",
justifyContent: "space-between",
};
return (
<footer style={style}>
<Button>About</Button>
<Button>Jobs</Button>
<CartButton />
</footer>
);
}
function App() {
return (
<main>
<Header />
<h1>Welcome to the shop!</h1>
<BorderContext.Provider value={2}> #4
<Footer />
</BorderContext.Provider>
</main>
);
}
export default App;
Inspect the complete BorderContext example, including the default value, Button consumer, cart-specific provider, header, and footer. section 10.1.3
