Part 09 / Stage 2
useContext
Goal: Recognize prop-drilling pain for what it actually is (components forced to know about a value they never use, purely to forward it), create and provide a context, consume it with
useContext, keep state and the Provider that owns it in one place, knowcreateContext's default-value rule, split contexts to limit unnecessary re-renders, and wrap a context in a custom hook that fails loudly when used outside its Provider. Time: ~4 hours · Level: comfortable withuseStateand lifting state up (Part 3)
What you will learn
- What prop drilling actually costs: not "it's broken" - it works - but every intermediate component between the state and the component that needs it has to mention a value it never reads itself, purely to forward it
createContext,<SomeContext.Provider value={...}>, anduseContext(SomeContext)- the three pieces that let a value skip every intermediate component entirely- Context does not replace
useState- theProvidercomponent still owns a realuseStatecall; context only changes how far that value and its setters can reach, not where they live createContext(defaultValue)'s one real job: what a consumer gets back if it renders with no matching Provider above it anywhere - not a "starting state," a fallback for an unwired tree- Context's performance ceiling: every component that calls
useContexton a given context re-renders whenever that Provider's value changes, whether or not that specific consumer reads the part that changed - and a new object literal passed asvalueon every Provider render defeats even careful splitting - Splitting one bundled context into several narrower ones, so a consumer of context A never re-renders because context B's value changed
- Wrapping
useContextin a small custom hook (useTheme(),useAuth()) that throws a clear, specific error when called with no Provider above it, instead of every consumer crashing later on a confusingundefinedaccess - This part's running examples: a theme toggle threaded through pass-through components, the same toggle rebuilt with context, a "logged in as Asha" auth context, a currency default-value probe, a combined-vs-split theme/user context with render counters, and a
useTheme()hook with a safety throw
A note on how this part is organised: same convention as Parts 1-8 - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below.
Topics in this part
Practice
Every exercise below is a React component (or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course. Exercises involving render counts use a useRef counter the same way examples/05_splitting_contexts_for_rerenders.jsx does.
Exercise 1: A first context - app language, two levels deep
Scenario: A Swiggy-style app wants an "English"/"हिंदी" language toggle available to a settings row buried inside a menu, with nothing in between caring what language is selected.
What to do: Write LanguageContext = createContext(null), a LanguageProvider({ children }) owning useState("en") plus a toggleLanguage function, a pass-through SettingsMenu (no language-shaped prop anywhere on it), and a LanguageRow two levels down that reads { language, toggleLanguage } via useContext.
Sample output (really run):
initial render -> "Language: en"
click "Toggle language" -> "Language: hi"
click again -> "Language: en"
💡 Hint: this is examples/02_create_context_provider_consumer.jsx's exact shape, renamed - createContext, a Provider owning the state, a pass-through component with nothing language-related in its signature, and a consumer two levels down.
Exercise 2: Context + state at the provider - a shared cart count
Scenario: Part 7's Exercise 6 proved that two components each calling useLocalStorage("cart-count", 0) independently never stay in sync, and fixed it by lifting the hook call up to a shared parent passing props down. Do the same fix with context instead, for a header icon and a cart side panel that are not parent/child of each other.
What to do: Write CartContext = createContext(null), a CartProvider({ children }) owning one useState(0) plus addItem/clearCart functions, and two unrelated siblings, HeaderCartIcon and CartSidePanel, each reading { count, addItem } via useContext(CartContext) independently.
Sample output (really run, click "Add item" inside HeaderCartIcon):
before: HeaderCartIcon "Cart: 0", CartSidePanel "Cart: 0"
after: HeaderCartIcon "Cart: 1", CartSidePanel "Cart: 1" - both updated, no prop connecting them
💡 Hint: this is examples/03_context_plus_state_at_provider.jsx's AccountMenu/GreetingBanner shape exactly - one useState at the Provider, two independent siblings reading the same context.
Exercise 3: Find and fix a default-value misunderstanding
Scenario: A teammate read about createContext(defaultValue) and assumed it was the Provider's starting state, so they skipped writing a Provider entirely and just called useContext directly:
const DeliverySlotContext = createContext("9 AM - 12 PM");
export function DeliverySlotBannerBroken() {
const slot = useContext(DeliverySlotContext);
return <p>Delivery slot: {slot}</p>;
}
export function DeliverySlotPicker({ onPick }) {
// Calls onPick("2 PM - 5 PM") when a slot button is clicked - but there is
// no Provider anywhere, so DeliverySlotBannerBroken never finds out.
}
Picking a new slot in DeliverySlotPicker never changes what DeliverySlotBannerBroken shows - it is permanently stuck on the default.
What to do: Write DeliverySlotBannerBroken (the code above, unchanged) alongside a DeliverySlotProvider/DeliverySlotBannerFixed pair that actually owns the slot in useState at a Provider, with DeliverySlotPicker calling a function from context instead of a prop.
Sample output (really run, pick "2 PM - 5 PM"):
DeliverySlotBannerBroken: "Delivery slot: 9 AM - 12 PM" forever (no Provider, always the default)
DeliverySlotBannerFixed: "Delivery slot: 2 PM - 5 PM" after picking
💡 Hint: this part's Section 4 names the rule directly - a context's default is a fallback for an unwired tree, never a substitute for a real Provider owning real state.
Exercise 4: Find and fix a context split that didn't actually help
Scenario: A teammate split a combined context into CartContext and WishlistContext to stop an unrelated re-render problem, but a reviewer says the render counts prove it didn't work:
function StoreProviderBroken({ children }) {
const [cartCount, setCartCount] = useState(0);
const [wishlistCount] = useState(0);
return (
<WishlistContext.Provider value={{ wishlistCount }}>
<CartContext.Provider value={{ cartCount, setCartCount }}>{children}</CartContext.Provider>
</WishlistContext.Provider>
);
}
What to do: Write StoreProviderBroken (the code above, unchanged, with render-count data-testids on a CartDisplay and a WishlistDisplay, the same shape as examples/05_splitting_contexts_for_rerenders.jsx) and StoreProviderFixed, where WishlistContext.Provider's value is the already-stable wishlistCount passed directly, not re-wrapped in { wishlistCount } on every render. Prove, with the render counters, that incrementing the cart count re-renders WishlistDisplay in the broken version but not in the fixed one.
Sample output (really run, increment the cart count twice):
Broken: WishlistDisplay's render count climbs on every cart increment (1 -> 2 -> 3)
Fixed: WishlistDisplay's render count stays at 1 the entire time
💡 Hint: this part's Section 5 names this exact gotcha - a fresh object literal passed as a Provider's value has a new reference every render, which re-renders every consumer of that context regardless of whether the data inside changed.
Exercise 5: Split an over-rendering checkout context
Scenario: A checkout page bundles a delivery address editor and a payment-method summary into one CheckoutContext, and a profiler shows the payment summary re-rendering every time the address textbox changes - a real, measurable cost on a page with a lot more going on below it.
What to do: Write CheckoutProviderBroken (one CheckoutContext holding both address/setAddress and paymentMethod/setPaymentMethod) with an AddressEditor and a PaymentSummary, each with a render-count data-testid. Then write CheckoutProviderFixed, splitting into AddressContext and PaymentContext, each with its own stable (non-re-wrapped) value, and the matching AddressEditorFixed/PaymentSummaryFixed.
Sample output (really run, type three characters into the address field):
Broken: PaymentSummary's render count climbs by 3 (once per keystroke) even though payment never changed
Fixed: PaymentSummary's render count stays at 1 the entire time
💡 Hint: this is examples/05_splitting_contexts_for_rerenders.jsx's combined-vs-split pattern end to end, on a new domain - split along "what changes together," and remember Exercise 4's object-literal gotcha when wiring the fixed Provider's values.
Exercise 6: A useCart() hook with a safety throw
Scenario: A cart icon component is sometimes rendered in a Storybook-style isolated preview with no app shell around it, and currently crashes there with a confusing "Cannot read properties of undefined" instead of a clear message pointing at the missing CartProvider.
What to do: Write CartContext = createContext(undefined), CartProvider({ children }) (a real useState(0) plus addItem/clearCart), and useCart(), a custom hook wrapping useContext(CartContext) that throws "useCart must be called inside a <CartProvider>" when the context is undefined. Write CartIcon() using useCart(), and prove both the happy path (inside a CartProvider) and the throw (rendered alone, with console.error silenced the same way examples/06_custom_use_hook_with_safety_throw.test.jsx does).
Sample output (really run):
<CartProvider><CartIcon /></CartProvider>: renders "Cart: 0", "Add item" click -> "Cart: 1"
<CartIcon /> alone: throws "useCart must be called inside a <CartProvider>"
💡 Hint: this is examples/06_custom_use_hook_with_safety_throw.jsx's exact shape - createContext(undefined) so "no Provider" has one unambiguous signal to check against, and the throw happens inside the hook, not inside every component that calls it.
Show the solutions for Part 9 (12 files)
solutions/ex01_language_context.jsx
// Exercise 1 solution: same shape as
// examples/02_create_context_provider_consumer.jsx - a Provider owning the
// state, one pass-through component with nothing language-related in its
// signature, and a consumer two levels down.
import { createContext, useContext, useState } from "react";
const LanguageContext = createContext(null);
export function LanguageProvider({ children }) {
const [language, setLanguage] = useState("en");
function toggleLanguage() {
setLanguage((current) => (current === "en" ? "hi" : "en"));
}
return (
<LanguageContext.Provider value={{ language, toggleLanguage }}>{children}</LanguageContext.Provider>
);
}
// Pure pass-through - no language prop anywhere on this signature.
export function SettingsMenu() {
return (
<div>
<LanguageRow />
</div>
);
}
function LanguageRow() {
const { language, toggleLanguage } = useContext(LanguageContext);
return (
<div>
<p>Language: {language}</p>
<button onClick={toggleLanguage}>Toggle language</button>
</div>
);
}
solutions/ex01_language_context.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { LanguageProvider, SettingsMenu } from "./ex01_language_context.jsx";
describe("LanguageProvider + SettingsMenu", () => {
it("really toggles the language through a pass-through component with no language prop", async () => {
const user = userEvent.setup();
render(
<LanguageProvider>
<SettingsMenu />
</LanguageProvider>,
);
expect(screen.getByText("Language: en")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Toggle language" }));
expect(screen.getByText("Language: hi")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Toggle language" }));
expect(screen.getByText("Language: en")).toBeInTheDocument();
});
});
solutions/ex02_shared_cart_count.jsx
// Exercise 2 solution: same shape as
// examples/03_context_plus_state_at_provider.jsx - one useState at the
// Provider, two unrelated siblings reading the same context independently.
import { createContext, useContext, useState } from "react";
const CartContext = createContext(null);
export function CartProvider({ children }) {
const [count, setCount] = useState(0);
function addItem() {
setCount((current) => current + 1);
}
function clearCart() {
setCount(0);
}
return <CartContext.Provider value={{ count, addItem, clearCart }}>{children}</CartContext.Provider>;
}
export function HeaderCartIcon() {
const { count, addItem } = useContext(CartContext);
return (
<div>
<p>Cart: {count}</p>
<button onClick={addItem}>Add item</button>
</div>
);
}
export function CartSidePanel() {
const { count } = useContext(CartContext);
return <p>Cart: {count}</p>;
}
solutions/ex02_shared_cart_count.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { CartProvider, CartSidePanel, HeaderCartIcon } from "./ex02_shared_cart_count.jsx";
describe("CartProvider + HeaderCartIcon + CartSidePanel", () => {
it("really keeps both unrelated siblings in sync from one shared context, no props connecting them", async () => {
const user = userEvent.setup();
render(
<CartProvider>
<HeaderCartIcon />
<CartSidePanel />
</CartProvider>,
);
const cartTexts = screen.getAllByText("Cart: 0");
expect(cartTexts).toHaveLength(2);
await user.click(screen.getByRole("button", { name: "Add item" }));
expect(screen.getAllByText("Cart: 1")).toHaveLength(2);
});
});
solutions/ex03_delivery_slot_default_misuse.jsx
// Exercise 3 solution: the broken half skips a Provider entirely, assuming
// createContext's default IS the live state (Section 4's exact mistake).
// The fixed half owns the slot in real useState at a real Provider.
import { createContext, useContext, useState } from "react";
const DeliverySlotContext = createContext("9 AM - 12 PM");
export function DeliverySlotBannerBroken() {
const slot = useContext(DeliverySlotContext);
return <p>Delivery slot: {slot}</p>;
}
export function DeliverySlotPickerBroken({ onPick }) {
return (
<div>
<button onClick={() => onPick("2 PM - 5 PM")}>Pick 2 PM - 5 PM</button>
</div>
);
}
export function DeliverySlotProvider({ children }) {
const [slot, setSlot] = useState("9 AM - 12 PM");
return (
<DeliverySlotContext.Provider value={{ slot, pickSlot: setSlot }}>{children}</DeliverySlotContext.Provider>
);
}
export function DeliverySlotBannerFixed() {
const { slot } = useContext(DeliverySlotContext);
return <p>Delivery slot: {slot}</p>;
}
export function DeliverySlotPickerFixed() {
const { pickSlot } = useContext(DeliverySlotContext);
return (
<div>
<button onClick={() => pickSlot("2 PM - 5 PM")}>Pick 2 PM - 5 PM</button>
</div>
);
}
solutions/ex03_delivery_slot_default_misuse.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import {
DeliverySlotBannerBroken,
DeliverySlotBannerFixed,
DeliverySlotPickerBroken,
DeliverySlotPickerFixed,
DeliverySlotProvider,
} from "./ex03_delivery_slot_default_misuse.jsx";
describe("DeliverySlotBannerBroken - no Provider, permanently stuck on the default", () => {
it("really never changes after picking a new slot - there is no Provider to update", async () => {
const user = userEvent.setup();
let pickedSlot = null;
render(
<div>
<DeliverySlotBannerBroken />
<DeliverySlotPickerBroken onPick={(slot) => (pickedSlot = slot)} />
</div>,
);
expect(screen.getByText("Delivery slot: 9 AM - 12 PM")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Pick 2 PM - 5 PM" }));
expect(pickedSlot).toBe("2 PM - 5 PM"); // the picker's own callback did fire
// ...but the banner reads a context with no Provider above it, so it is
// still showing createContext's default, not the picked value.
expect(screen.getByText("Delivery slot: 9 AM - 12 PM")).toBeInTheDocument();
});
});
describe("DeliverySlotProvider + DeliverySlotBannerFixed + DeliverySlotPickerFixed", () => {
it("really updates the banner once a real Provider owns the slot", async () => {
const user = userEvent.setup();
render(
<DeliverySlotProvider>
<DeliverySlotBannerFixed />
<DeliverySlotPickerFixed />
</DeliverySlotProvider>,
);
expect(screen.getByText("Delivery slot: 9 AM - 12 PM")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Pick 2 PM - 5 PM" }));
expect(screen.getByText("Delivery slot: 2 PM - 5 PM")).toBeInTheDocument();
});
});
solutions/ex04_store_context_object_wrap.jsx
// Exercise 4 solution: the broken half DOES split into two contexts, but
// still re-wraps WishlistContext's value in a new { wishlistCount } object
// literal on every render of the Provider - which changes its reference
// every time regardless of whether wishlistCount itself changed, defeating
// the split. The fixed half passes the already-stable primitive directly.
import { createContext, useContext, useRef, useState } from "react";
const CartContext = createContext(null);
const WishlistContext = createContext(null);
export function StoreProviderBroken({ children }) {
const [cartCount, setCartCount] = useState(0);
const [wishlistCount] = useState(0);
function incrementCart() {
setCartCount((current) => current + 1);
}
return (
<WishlistContext.Provider value={{ wishlistCount }}>
<CartContext.Provider value={{ cartCount, incrementCart }}>{children}</CartContext.Provider>
</WishlistContext.Provider>
);
}
export function StoreProviderFixed({ children }) {
const [cartCount, setCartCount] = useState(0);
const [wishlistCount] = useState(0);
function incrementCart() {
setCartCount((current) => current + 1);
}
return (
<WishlistContext.Provider value={wishlistCount}>
<CartContext.Provider value={{ cartCount, incrementCart }}>{children}</CartContext.Provider>
</WishlistContext.Provider>
);
}
export function CartDisplay() {
const { cartCount, incrementCart } = useContext(CartContext);
return (
<div>
<p>Cart: {cartCount}</p>
<button onClick={incrementCart}>Add to cart</button>
</div>
);
}
export function WishlistDisplayBroken() {
const { wishlistCount } = useContext(WishlistContext);
const renderCountRef = useRef(0);
renderCountRef.current += 1;
return (
<div>
<p>Wishlist: {wishlistCount}</p>
<p data-testid="wishlist-render-count">{renderCountRef.current}</p>
</div>
);
}
export function WishlistDisplayFixed() {
const wishlistCount = useContext(WishlistContext);
const renderCountRef = useRef(0);
renderCountRef.current += 1;
return (
<div>
<p>Wishlist: {wishlistCount}</p>
<p data-testid="wishlist-render-count">{renderCountRef.current}</p>
</div>
);
}
solutions/ex04_store_context_object_wrap.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import {
CartDisplay,
StoreProviderBroken,
StoreProviderFixed,
WishlistDisplayBroken,
WishlistDisplayFixed,
} from "./ex04_store_context_object_wrap.jsx";
describe("StoreProviderBroken - WishlistContext's value is re-wrapped in a new object every render", () => {
it("really re-renders WishlistDisplay on every cart increment, even though wishlistCount never changes", async () => {
const user = userEvent.setup();
render(
<StoreProviderBroken>
<CartDisplay />
<WishlistDisplayBroken />
</StoreProviderBroken>,
);
expect(screen.getByTestId("wishlist-render-count")).toHaveTextContent("1");
await user.click(screen.getByRole("button", { name: "Add to cart" }));
expect(screen.getByTestId("wishlist-render-count")).toHaveTextContent("2");
await user.click(screen.getByRole("button", { name: "Add to cart" }));
expect(screen.getByTestId("wishlist-render-count")).toHaveTextContent("3");
});
});
describe("StoreProviderFixed - WishlistContext's value is the stable primitive itself", () => {
it("really leaves WishlistDisplay's render count untouched by cart increments", async () => {
const user = userEvent.setup();
render(
<StoreProviderFixed>
<CartDisplay />
<WishlistDisplayFixed />
</StoreProviderFixed>,
);
expect(screen.getByTestId("wishlist-render-count")).toHaveTextContent("1");
await user.click(screen.getByRole("button", { name: "Add to cart" }));
await user.click(screen.getByRole("button", { name: "Add to cart" }));
expect(screen.getByTestId("wishlist-render-count")).toHaveTextContent("1");
});
});
solutions/ex05_checkout_context_split.jsx
// Exercise 5 solution: same shape as
// examples/05_splitting_contexts_for_rerenders.jsx, on a checkout page -
// one bundled context forces an unrelated PaymentSummary to re-render on
// every address keystroke; splitting (with stable, non-re-wrapped values)
// fixes it.
import { createContext, useContext, useRef, useState } from "react";
// --- Broken: one context for both address and payment ---
const CheckoutContextBroken = createContext(null);
export function CheckoutProviderBroken({ children }) {
const [address, setAddress] = useState("");
const [paymentMethod] = useState("UPI");
return (
<CheckoutContextBroken.Provider value={{ address, setAddress, paymentMethod }}>
{children}
</CheckoutContextBroken.Provider>
);
}
export function AddressEditorBroken() {
const { address, setAddress } = useContext(CheckoutContextBroken);
return (
<input
aria-label="Delivery address"
value={address}
onChange={(event) => setAddress(event.target.value)}
/>
);
}
export function PaymentSummaryBroken() {
const { paymentMethod } = useContext(CheckoutContextBroken);
const renderCountRef = useRef(0);
renderCountRef.current += 1;
return (
<div>
<p>Payment method: {paymentMethod}</p>
<p data-testid="broken-payment-render-count">{renderCountRef.current}</p>
</div>
);
}
// --- Fixed: address and payment each get their own context ---
const AddressContext = createContext(null);
const PaymentContext = createContext(null);
export function CheckoutProviderFixed({ children }) {
const [address, setAddress] = useState("");
const [paymentMethod] = useState("UPI");
return (
<PaymentContext.Provider value={paymentMethod}>
<AddressContext.Provider value={{ address, setAddress }}>{children}</AddressContext.Provider>
</PaymentContext.Provider>
);
}
export function AddressEditorFixed() {
const { address, setAddress } = useContext(AddressContext);
return (
<input
aria-label="Delivery address"
value={address}
onChange={(event) => setAddress(event.target.value)}
/>
);
}
export function PaymentSummaryFixed() {
const paymentMethod = useContext(PaymentContext);
const renderCountRef = useRef(0);
renderCountRef.current += 1;
return (
<div>
<p>Payment method: {paymentMethod}</p>
<p data-testid="fixed-payment-render-count">{renderCountRef.current}</p>
</div>
);
}
solutions/ex05_checkout_context_split.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import {
AddressEditorBroken,
AddressEditorFixed,
CheckoutProviderBroken,
CheckoutProviderFixed,
PaymentSummaryBroken,
PaymentSummaryFixed,
} from "./ex05_checkout_context_split.jsx";
describe("CheckoutProviderBroken - one context for address and payment", () => {
it("really re-renders PaymentSummary on every address keystroke", async () => {
const user = userEvent.setup();
render(
<CheckoutProviderBroken>
<AddressEditorBroken />
<PaymentSummaryBroken />
</CheckoutProviderBroken>,
);
expect(screen.getByTestId("broken-payment-render-count")).toHaveTextContent("1");
await user.type(screen.getByLabelText("Delivery address"), "221");
// One render per keystroke - 3 characters typed, 1 (initial) + 3 = 4.
expect(screen.getByTestId("broken-payment-render-count")).toHaveTextContent("4");
});
});
describe("CheckoutProviderFixed - address and payment in separate contexts", () => {
it("really leaves PaymentSummary's render count untouched by address keystrokes", async () => {
const user = userEvent.setup();
render(
<CheckoutProviderFixed>
<AddressEditorFixed />
<PaymentSummaryFixed />
</CheckoutProviderFixed>,
);
expect(screen.getByTestId("fixed-payment-render-count")).toHaveTextContent("1");
await user.type(screen.getByLabelText("Delivery address"), "221");
expect(screen.getByTestId("fixed-payment-render-count")).toHaveTextContent("1");
expect(screen.getByLabelText("Delivery address")).toHaveValue("221");
});
});
solutions/ex06_use_cart_safety_throw.jsx
// Exercise 6 solution: same shape as
// examples/06_custom_use_hook_with_safety_throw.jsx - createContext(undefined)
// so "no Provider" has one unambiguous signal, and the throw lives inside
// the hook, not inside every component that calls it.
import { createContext, useContext, useState } from "react";
const CartContext = createContext(undefined);
export function CartProvider({ children }) {
const [count, setCount] = useState(0);
function addItem() {
setCount((current) => current + 1);
}
function clearCart() {
setCount(0);
}
return <CartContext.Provider value={{ count, addItem, clearCart }}>{children}</CartContext.Provider>;
}
export function useCart() {
const context = useContext(CartContext);
if (context === undefined) {
throw new Error("useCart must be called inside a <CartProvider>");
}
return context;
}
export function CartIcon() {
const { count, addItem } = useCart();
return (
<div>
<p>Cart: {count}</p>
<button onClick={addItem}>Add item</button>
</div>
);
}
solutions/ex06_use_cart_safety_throw.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { CartIcon, CartProvider } from "./ex06_use_cart_safety_throw.jsx";
describe("CartIcon inside a CartProvider", () => {
it("really renders the live count and updates it on click", async () => {
const user = userEvent.setup();
render(
<CartProvider>
<CartIcon />
</CartProvider>,
);
expect(screen.getByText("Cart: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Add item" }));
expect(screen.getByText("Cart: 1")).toBeInTheDocument();
});
});
describe("CartIcon rendered alone, with no CartProvider above it", () => {
it("really throws a clear error instead of crashing confusingly later", () => {
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => render(<CartIcon />)).toThrow("useCart must be called inside a <CartProvider>");
consoleErrorSpy.mockRestore();
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Threading a value through several components that never read it themselves, just to reach one deep consumer | Every intermediate component's signature has to mention a value it doesn't use, and adding another such value means editing every one of them again | Move the value into a context once it needs to skip two or more components that don't use it (Sections 1-2) |
Treating createContext(defaultValue) as the Provider's starting state |
The default is only ever used when a consumer has no matching Provider above it at all - a Provider's own value always wins once one exists |
Seed real starting state with useState inside the component that renders the Provider, not in createContext's argument (Sections 3-4) |
Building a context's value as a fresh object literal on every render of the Provider, assuming splitting contexts alone is enough |
A new object has a new reference every render, so every consumer of that context re-renders anyway - even one holding data that never actually changed | Pass an already-stable value straight through (as examples/05...jsx's value={user} does), or wrap a genuinely-recomputed object in useMemo (Section 5) |
| Bundling every piece of shared state into one big context "to keep it simple" | Any single piece changing re-renders every consumer of the whole context, even ones that only read an unrelated field | Split into separate contexts along the lines of what actually changes together (Section 5) |
Calling useContext(SomeContext) directly everywhere, with no check for a missing Provider |
A consumer rendered outside its Provider either gets a confusing undefined-shaped crash deep inside its own code, or silently uses a default that was never meant to be real data |
Wrap it in a small custom hook (useTheme, useAuth) that throws one clear, specific error the moment it detects no Provider (Section 6) |
| Reaching for context the moment two components need to share anything, instead of first trying to lift state up to their nearest common parent | Context adds its own re-render ceiling and an extra layer of indirection - not free, and not needed for state only a couple of nearby components share | Try lifting state up (Part 3) first; reach for context specifically when prop drilling would otherwise skip two or more components that don't use the value (Section 1) |
Quick recap
- Prop drilling isn't broken, it's expensive: every intermediate component between the state and its real consumer has to know about a value it never reads, purely to forward it.
createContext+<SomeContext.Provider value={...}>+useContext(SomeContext)let a value skip every intermediate component - the Provider still owns a realuseStatecall; context only changes how far that value reaches.createContext(defaultValue)'s default is a fallback for a consumer with no Provider above it anywhere - never a Provider's starting state, which always comes fromuseStateinstead.- Every consumer of a context re-renders whenever that context's value changes, whether or not that specific consumer reads the part that changed - and a freshly-built object literal passed as
valueon every Provider render changes identity every time regardless of the underlying data, which can quietly defeat a split you already did. - Splitting one bundled context into several narrower ones, each only holding what actually changes together, raises that re-render ceiling back up with no other code change.
- A small custom hook wrapping
useContextcan throw one clear, specific error the instant it's used with no Provider above it, instead of letting every consumer discover that the confusing way, later, on its own.
Checklist
- I can say, in one sentence, what prop drilling actually costs (not "it's broken" - maintenance, because intermediate components must know about values they never use).
- I created a context, wrapped a tree in its
Provider, and read it from a component two or more levels deep withuseContext- with nothing in between mentioning that value. - I wrote a
Providercomponent that owns a realuseStatecall and hands both the value and the functions that change it down through context. - I proved
createContext's default-value rule myself - rendered a consumer with no Provider above it and watched the default appear, then wrapped it in a Provider and watched that override it. - I reproduced the Section 5 re-render-ceiling problem myself (two unrelated pieces of state in one context, a render counter proving both consumers re-render on either change), then split the context and proved only the relevant consumer re-renders afterward.
- I wrote a custom hook wrapping a context that throws a clear error when its Provider is missing, and proved both the happy path and the throw with a real test.