JAVASCRIPT

Implement Persistent Dark Mode with `useDarkMode` React Hook

Build a custom `useDarkMode` React hook that manages and persists dark mode state using local storage, providing a seamless user experience across sessions.

import { useState, useEffect } from 'react';

function useDarkMode() {
  const [enabled, setEnabled] = useState(() => {
    if (typeof localStorage === 'undefined') return false;
    const storedValue = localStorage.getItem('darkMode');
    return storedValue ? JSON.parse(storedValue) : window.matchMedia('(prefers-color-scheme: dark)').matches;
  });

  useEffect(() => {
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem('darkMode', JSON.stringify(enabled));
    }
    const className = 'dark-mode';
    const element = window.document.body;
    if (enabled) {
      element.classList.add(className);
    } else {
      element.classList.remove(className);
    }
  }, [enabled]);

  return [enabled, setEnabled];
}
How it works: This custom `useDarkMode` hook manages and persists the user's dark mode preference. It initializes its state from `localStorage` if available, falling back to the system's preferred color scheme via `window.matchMedia`. The `useEffect` hook ensures that `localStorage` is updated and a `dark-mode` CSS class is toggled on the document's `body` element whenever the `enabled` state changes, allowing CSS to apply corresponding styles for a consistent user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs