usePreferredTheme

Resolves the effective theme by reconciling system preferences and manual user selection.

Important

This hook automatically updates the class and color-scheme of the html element. Ensure your CSS is configured to use the .dark class or CSS variables for a seamless transition.

Tip

Setting setUserTheme(null) will remove the override from localStorage and return the application to following the system-level OS theme (Light or Dark mode).

Installation

bash

Description

This hook manages dark/light mode logic. It monitors the prefers-color-scheme media query for system changes and allows users to override this via localStorage. It provides a utility function toggleTheme to switch between modes easily.

Return values

NameTypeDescription
themeThemeThe active theme string (e.g., 'light' or 'dark').
setUserTheme(theme: Theme | null) => voidManually set a theme or reset to system by passing null.
systemThemeThemeThe theme preference reported by the OS.
userThemeTheme | nullThe stored user override, if it exists.
toggleTheme(options?: { dark?: Theme; light?: Theme }) => voidToggles between two themes (defaults to 'dark'/'light').

Demo

Theme Manager

System: lightUser: Follow system

Source code

tsx