Implement Persistent Light and Dark Theme Toggle | Gatsby DevSnips - A modern, fast, and developer-friendly collection of HTML, CSS, and JavaScript component snippets - built with Gatsby and TailwindCSS.
Implement Persistent Light and Dark Theme Toggle

Implement Persistent Light and Dark Theme Toggle

March 3, 2026

A theme switch should remember user preference and feel instant on every page. This snippet shows a reliable setup using React context, CSS variables, and localStorage.

Core behavior

  • Read saved theme from localStorage
  • Fallback to system preference if no saved value exists
  • Apply dark class on <html>
  • Persist changes when user toggles mode

Why CSS variables help

Using variables like --background, --text-primary, and --text-contrast makes theming scalable. You only switch variable values for dark mode while components continue using the same class names.

Accessibility check

Ensure the toggle button has an aria-label, aria-pressed, and visible focus state for keyboard users.