Community JavaScript Snippet

The Theme-Switcher Context I Drop Into Every App

The drop-in `<ThemeProvider>` I keep in my dotfiles. CSS variables, `prefers-color-scheme` integration, and `localStorage` persistence in about 60 lines.

The Theme-Switcher Context I Drop Into Every App

The drop-in `<ThemeProvider>` I keep in my dotfiles. CSS variables, `prefers-color-scheme` integration, and `localStorage` persistence in about 60 lines.

JavaScript
Frontend
3 snippets
react
hooks
css-variables
kiranpatel

By @kiranpatel

November 30, 2025

·

Updated May 18, 2026

654 views

10

4.3 (13)

I keep the token table in a plain object because I want any colour change to be a one-line edit, not a styled-components migration. The useEffect writes the active set onto documentElement so children read var(--bg) directly without re-rendering on theme flips, which is the whole performance reason to do this with CSS variables instead of context-driven inline styles. Wrapping the value in useMemo keyed on theme is the same idea as the dedicated context-memoization snippet; without it every parent re-render would refresh consumers. The default fallback in createContext matters because it is what useTheme() returns when a consumer is rendered outside the provider, and silently broken theming is worse than a thrown error in development.