Skip to content

Instantly share code, notes, and snippets.

@tlux
Created December 14, 2025 16:04
Show Gist options
  • Select an option

  • Save tlux/9f5552d5129c218333b90e81ebfdacf6 to your computer and use it in GitHub Desktop.

Select an option

Save tlux/9f5552d5129c218333b90e81ebfdacf6 to your computer and use it in GitHub Desktop.
Hook to detect the preferred color scheme from the user agent
'use client';
import { useEffect, useState } from 'react';
type ColorScheme = 'light' | 'dark';
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
function getPreferredColorScheme(matches: boolean): ColorScheme {
return matches ? 'dark' : 'light';
}
export function usePreferredColorScheme() {
const [colorScheme, setColorScheme] = useState<ColorScheme>(
getPreferredColorScheme(mediaQuery.matches),
);
useEffect(() => {
const handler = (event: MediaQueryListEvent) => {
setColorScheme(getPreferredColorScheme(event.matches));
};
mediaQuery.addEventListener('change', handler);
return () => {
mediaQuery.removeEventListener('change', handler);
};
}, []);
return colorScheme;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment