useContext Internals: How Context Propagates Without Props

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 2

Context Value Quiz

Three context scenarios. Predict what value useContext returns β€” and understand the "nearest Provider" rule and the createContext default.

1
const ThemeContext = createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Sidebar />
    </ThemeContext.Provider>
  );
}

function Sidebar() {
  return <Button />;
}

function Button() {
  const theme = useContext(ThemeContext);
  return <button>{theme}</button>;
}

What does Button render?

2
const ThemeContext = createContext('light');

function Sidebar() {
  const theme = useContext(ThemeContext);
  return <div>{theme}</div>;
}

// Sidebar is rendered WITHOUT any Provider wrapping it

What value does Sidebar read?

3
<ThemeContext.Provider value="dark">
  <ThemeContext.Provider value="purple">
    <Button />
  </ThemeContext.Provider>
</ThemeContext.Provider>

What theme does Button read?

0/3 answered

πŸ’‘ Key rule: useContext always reads from the nearest Provider above it in the tree. If no Provider exists, it falls back to the createContext default.

2

Exercise 2 of 2

Build a Theme Context

Live editor: wire up createContext + Provider + useContext to share theme state without prop drilling. ThemeToggle and ThemedBox need no props.

Task

Wire up ThemeContext so ThemeToggle and ThemedBox can read the theme and toggle it β€” without Header receiving any props at all.

  1. Create ThemeContext with createContext
  2. Wrap App's return in a ThemeContext.Provider
  3. Consume { theme, toggleTheme } via useContext in both leaf components
Loading editor…
Practice: useContext Internals: How Context Propagates Without Props β€” Interactive Exercises | Durgesh Rai