Context API: Theme Switcher
Mission
Solve prop drilling with the Context API so global data, like a visual theme, is available anywhere without passing props by hand.
Tasks
- 1
Create and export a
ThemeContextwithcreateContext(). - 2
Implement
ThemeProviderso it owns the theme state ('light'or'dark') and atoggleThemefunction. - 3
Pass both the theme and the toggle through the Provider's
valueprop. - 4
Wrap
NavbarandContentinApp.jswith yourThemeProvider. - 5
Consume the context in
Navbar.jsandContent.jswithuseContext.
import React from 'react'; import Navbar from './components/Navbar'; import Content from './components/Content'; import { ThemeProvider } from './context/ThemeContext'; import './styles.css'; export default function App() { // Tip: wrap Navbar and Content with the right Provider return ( <div className="app-container"> <Navbar /> <Content /> </div> ); }
Requirements
0/8ThemeContext is created with createContext() (not run yet)
ThemeProvider keeps the theme in state, starting as 'light' (not run yet)
toggleTheme updates the state (not run yet)
The Provider's value contains { theme, toggleTheme } (not run yet)
App wraps Navbar and Content with <ThemeProvider> (not run yet)
Navbar and Content receive no props from App (not run yet)
Navbar reads the context and calls toggleTheme from the button (not run yet)
Content gets the theme from the context (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.