Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isDarkModePreferred

Checks if the user's system prefers dark color scheme.

TypeScript
Copied!
1/**
2 * Checks if the user's system prefers dark color scheme.
3 *
4 * @returns True if dark mode is preferred, false otherwise.
5 */
6export function isDarkModePreferred(): boolean {
7  if (typeof window === 'undefined' || !window.matchMedia) return false;
8  return window.matchMedia('(prefers-color-scheme: dark)').matches;
9}
  • Modern Standards-Based Detection

    Utilizes the prefers-color-scheme media query, a widely supported CSS feature, for accurate theme preference detection.

  • Safe for Server and Legacy Environments

    Includes checks to ensure compatibility with non-browser or older environments lacking window or matchMedia.

  • Real-Time Preference Awareness

    Enables responsive theming based on user system settings without requiring manual input.

  • Simple and Minimalist API

    Provides a focused boolean return, making it easy to integrate into conditional logic.

Tests | Examples

TypeScript
Copied!
1const originalMatchMedia = window.matchMedia;
2
3afterEach(() => {
4  window.matchMedia = originalMatchMedia;
5});
6
7test('returns true when prefers-color-scheme is dark', () => {
8  window.matchMedia = jest.fn().mockImplementation(query => ({
9    matches: query === '(prefers-color-scheme: dark)',
10    media: query,
11    onchange: null,
12    addEventListener: jest.fn(),
13    removeEventListener: jest.fn(),
14    dispatchEvent: jest.fn(),
15  }));
16  expect(isDarkModePreferred()).toBe(true);
17});
18
19test('returns false when prefers-color-scheme is light', () => {
20  window.matchMedia = jest.fn().mockImplementation(query => ({
21    matches: false,
22    media: query,
23    onchange: null,
24    addEventListener: jest.fn(),
25    removeEventListener: jest.fn(),
26    dispatchEvent: jest.fn(),
27  }));
28  expect(isDarkModePreferred()).toBe(false);
29});
30
31test('returns false in non-browser environment', () => {
32  const original = globalThis.window;
33  // @ts-expect-error
34  delete globalThis.window;
35  expect(isDarkModePreferred()).toBe(false);
36  globalThis.window = original;
37});

Common Use Cases

  • Applying Themed UI

    Automatically switch between light and dark themes based on user preference.

  • Personalizing User Experience

    Customize appearance without asking the user for explicit input.

  • Reducing Eye Strain

    Respect dark mode settings to improve comfort in low-light environments.

  • Dynamic Styling in SPAs

    Adjust application styles on load or when preferences change via listeners.

Codebase: Utilities -> Platforms -> isDarkModePreferred | Yevhen Klymentiev