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
- Create a ThemeContext with
lightanddarkstates - Read saved preference from
localStorageon mount - Apply a class to
document.documentElementbased on state - Define CSS variables for colors in both themes
- 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