JAVASCRIPT

React `useColorScheme` Hook for Dark Mode Detection

Implement a custom React hook to detect the user's preferred color scheme (light or dark mode) using CSS `prefers-color-scheme` media query for dynamic theming.

import { useState, useEffect } from 'react';

const getPreferredColorScheme = () => {
  if (typeof window !== 'undefined' && window.matchMedia) {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  }
  return 'light'; // Default to light if not supported or server-side
};

function useColorScheme() {
  const [colorScheme, setColorScheme] = useState(getPreferredColorScheme);

  useEffect(() => {
    if (typeof window === 'undefined' || !window.matchMedia) {
      return;
    }

    const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');

    const handleChange = (e) => {
      setColorScheme(e.matches ? 'dark' : 'light');
    };

    mediaQueryList.addEventListener('change', handleChange);

    return () => {
      mediaQueryList.removeEventListener('change', handleChange);
    };
  }, []);

  return colorScheme;
}

export default useColorScheme;
How it works: The `useColorScheme` hook detects the user's operating system preference for a light or dark theme using the `prefers-color-scheme` media query. It initializes with the current preference and then listens for changes, automatically updating its state. This allows React components to render different styles or themes dynamically, providing a tailored user experience without requiring manual toggles.

Need help integrating this into your project?

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

Hire DigitalCodeLabs