0PricingLogin
React Academy · Lesson

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

  1. Detecting System Color Scheme
  2. CSS Variables for Theme Switching
  3. React Context for Theme State
  4. Persisting Theme and Preventing Flash
← Back to React Academy