Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 09 / Topic 6 of 6

A custom hook wrapping context, with a safety throw

Every consumer so far imports the context object directly and calls useContext(ThatContext) itself. A small custom hook on top buys two things: consumers never import the context object at all (just the hook), and the hook gets one place to check that a Provider actually exists above it. examples/06_custom_use_hook_with_safety_throw.jsx:

// examples/06_custom_use_hook_with_safety_throw.jsx
const ThemeContext = createContext(undefined); // undefined = "nobody provided one"

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error("useTheme must be called inside a <ThemeProvider>");
  }
  return context;
}

Calling useTheme() inside a <ThemeProvider> really returns the live { theme, toggleTheme } value and toggles it exactly like a direct useContext call would (examples/06_custom_use_hook_with_safety_throw.test.jsx). Rendering <ThemeToggleButton /> with no ThemeProvider anywhere above it really throws "useTheme must be called inside a <ThemeProvider>" immediately, instead of rendering something broken that fails confusingly later - this is this section's entire point, and the reason the context's default is undefined here rather than a usable fallback like Section 4's: undefined is reserved as the single unambiguous signal "no Provider," so the hook has something unmistakable to check against.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide