javascript 66 lines · 9 steps

Building a theme provider with React Context

A ThemeProvider that persists light/dark choice, follows the OS preference until the user overrides it, and shares state through context.

Explained by highlit
1import { createContext, useContext, useEffect, useState, useCallback } from 'react';
2 
3const ThemeContext = createContext(null);
4 
5const getInitialTheme = () => {
6 if (typeof window === 'undefined') return 'light';
7 const stored = window.localStorage.getItem('theme');
8 if (stored === 'light' || stored === 'dark') return stored;
9 return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
10};
11 
12export function ThemeProvider({ children }) {
13 const [theme, setTheme] = useState(getInitialTheme);
14 const [hasStoredPreference, setHasStoredPreference] = useState(
15 () => typeof window !== 'undefined' && window.localStorage.getItem('theme') != null
16 );
17 
18 useEffect(() => {
19 const root = document.documentElement;
20 root.classList.toggle('dark', theme === 'dark');
21 root.style.colorScheme = theme;
22 }, [theme]);
23 
24 useEffect(() => {
25 if (hasStoredPreference) return;
26 const media = window.matchMedia('(prefers-color-scheme: dark)');
27 const handleChange = (event) => setTheme(event.matches ? 'dark' : 'light');
28 media.addEventListener('change', handleChange);
29 return () => media.removeEventListener('change', handleChange);
30 }, [hasStoredPreference]);
31 
32 const toggleTheme = useCallback(() => {
33 setTheme((current) => {
34 const next = current === 'dark' ? 'light' : 'dark';
35 window.localStorage.setItem('theme', next);
36 return next;
37 });
38 setHasStoredPreference(true);
39 }, []);
40 
41 return (
42 <ThemeContext.Provider value={{ theme, toggleTheme }}>
43 {children}
44 </ThemeContext.Provider>
45 );
46}
47 
48export function useTheme() {
49 const context = useContext(ThemeContext);
50 if (!context) throw new Error('useTheme must be used within a ThemeProvider');
51 return context;
52}
53 
54export function ThemeToggle() {
55 const { theme, toggleTheme } = useTheme();
56 return (
57 <button
58 type="button"
59 onClick={toggleTheme}
60 aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
61 aria-pressed={theme === 'dark'}
62 >
63 {theme === 'dark' ? '\u2600\ufe0f' : '\ud83c\udf19'}
64 </button>
65 );
66}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A lazy state initializer lets you read localStorage or a media query once, safely, without re-running on every render.
  2. 2Guarding effects on SSR and on an explicit user preference keeps automatic behavior from fighting the user's choice.
  3. 3Throwing from the consumer hook turns a missing provider into a loud, immediate error instead of a silent null.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a theme provider with React Context — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code