create a react hook to check if it is dark mode in typescript

Here's an example of a TypeScript React hook that uses the useMedia hook to detect whether the user has a device that is set to dark mode:

import { useState, useEffect } from 'react';

function useDarkMode() {
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    setDarkMode(mediaQuery.matches);

    const listener = (event: MediaQueryListEvent) => {
      setDarkMode(event.matches);
    };

    mediaQuery.addEventListener('change', listener);
    return () => {
      mediaQuery.removeEventListener('change', listener);
    };
  }, []);

  return darkMode;
}

export default useDarkMode;
550 chars
24 lines

The hook uses window.matchMedia() to listen for changes in the user's system theme preference. If the user has their device set to dark mode, the hook returns true for darkMode, otherwise it returns false. This hook can be used in your React components to conditionally render based on the user's system theme preference.

gistlibby LogSnag