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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
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.