Theme Switcher

Crafting

npx shadcn add https://try.pungrumpy.com/r/theme-switcher.json

A component to switch between light, dark and system theme preferences with smooth animations and proper state management.

How It Works

The component supports both controlled and uncontrolled modes using @radix-ui/react-use-controllable-state. This hook provides a unified API that works seamlessly whether you want to manage the theme state externally or let the component handle it internally.

In uncontrolled mode, the component automatically detects the system preference using matchMedia and initializes the theme accordingly. When the user clicks the button, it cycles through the three available themes: system, light, and dark. Each transition is animated smoothly using motion.devmotion.dev for fluid, performant animations.

The theme preference is persisted to localStorage, ensuring the user's choice persists across page reloads. The component also listens for system preference changes, so if the user switches their OS theme while "system" mode is active, the UI updates automatically. Icons are provided by phosphoricons.comphosphoricons.com.

Usage

Uncontrolled Mode

The simplest way to use the component is in uncontrolled mode. The theme is determined by the system preference initially, and users can change it by clicking the button. The component handles all state management internally.

Was this helpful?