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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A lazy state initializer lets you read localStorage or a media query once, safely, without re-running on every render.
- 2Guarding effects on SSR and on an explicit user preference keeps automatic behavior from fighting the user's choice.
- 3Throwing from the consumer hook turns a missing provider into a loud, immediate error instead of a silent null.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
javascript
import { useState, useCallback, useRef } from 'react'; function LikeButton({ postId, initialLiked, initialCount }) { const [liked, setLiked] = useState(initialLiked);
Optimistic like button with React
optimistic-ui
abortcontroller
error-handling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-theme-provider-with-react-context-explained-javascript-7c2f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.