Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.
Exercise 1 of 2
Three context scenarios. Predict what value useContext returns β and understand the "nearest Provider" rule and the createContext default.
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?
const ThemeContext = createContext('light');
function Sidebar() {
const theme = useContext(ThemeContext);
return <div>{theme}</div>;
}
// Sidebar is rendered WITHOUT any Provider wrapping itWhat value does Sidebar read?
<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.
Exercise 2 of 2
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.
ThemeContext with createContextApp's return in a ThemeContext.Provider{ theme, toggleTheme } via useContext in both leaf components