React Context for Theme State
Build a ThemeProvider that exposes current theme and a toggle function to the entire component tree.
Creating ThemeContext
Start by calling createContext() with a default value that matches your context shape: const ThemeContext = createContext({ theme: 'light', toggleTheme: () => {} }). The default value is used only when a component reads the context without a parent Provider, which helps with testing isolated components.
The ThemeProvider Component
The ThemeProvider component is a wrapper that holds all theme logic. It reads the system preference on mount, manages the theme state, provides a toggleTheme function, and wraps children in ThemeContext.Provider value={{ theme, toggleTheme }}. Place it near the top of your component tree.
All lessons in this course
- Detecting System Color Scheme
- CSS Variables for Theme Switching
- React Context for Theme State
- Persisting Theme and Preventing Flash