How to implement dark mode in a React app

· Category: React

Short answer

Store the theme preference in state and localStorage, apply a data attribute or class to the document, and toggle CSS variables for colors. For optimizing theme-related renders, see how to optimize react renders with usememo and usecallback. For performance, see how to improve core web vitals.

Steps

  1. Create a ThemeContext with light and dark states
  2. Read saved preference from localStorage on mount
  3. Apply a class to document.documentElement based on state
  4. Define CSS variables for colors in both themes
  5. Provide a toggle button that updates state and storage

Tips

  • Respect the user's system preference with prefers-color-scheme
  • Avoid flash of incorrect theme by injecting a script in the head
  • For accessible UI patterns, review how to implement authentication in react