liveBook · Manning

Nested context

As explained in React Quickly, Second Edition

A nested context is a React Context arrangement in which one context provider is placed within another provider or provider subtree.

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

How React Quickly, Second Edition covers it

How deep it goes
Explains nearest-provider resolution, default fallback, and a complete button-border implementation.
Examples
Uses a shopping website whose header, footer, and cart buttons receive different border widths.
What you can do after
Apply it via React Context to implement shared UI values with nested, component-specific overrides.
How it connects
Connects React Context with providers, consumers, useContext, default values, and component trees.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.