Dark Mode Done Right

A comprehensive guide to implementing dark mode in your web applications with CSS custom properties and proper persistence.

Implementing dark mode properly requires more than just adding a class toggle. Here's my approach.

CSS Custom Properties

Define your color tokens as CSS custom properties:

:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.141 0.005 285.823);
}

.dark {
  --background: oklch(0.141 0.005 285.823);
  --foreground: oklch(0.985 0 0);
}

React Hook

Create a hook that handles:

1. Reading from localStorage

2. Falling back to system preference

3. Toggling the .dark class

4. Persisting the choice

Conclusion

Proper dark mode implementation improves user experience and accessibility.