Back to Specimen

UI

Theme Toggle

A smooth dark/light/system mode toggle with preference persistence and system detection.

React

Framer Motion

LocalStorage

Overview

This component provides a three-state theme toggle (Light → Dark → System) with smooth animated icon transitions. It persists user preference to localStorage and respects system preferences when set to “System” mode.

Live Demo

Key Features

  • Three States: Light, Dark, and System (follows OS preference)
  • Animated Transitions: Smooth icon morphing using Framer Motion
  • Persistence: Saves preference to localStorage
  • SSR Safe: Renders placeholder during hydration to avoid flash

Implementation Highlights

const cycleTheme = () => {
  const next: Record<ThemePreference, ThemePreference> = {
    system: 'light',
    light: 'dark',
    dark: 'system',
  };
  const newPreference = next[preference];
  setPreference(newPreference);

  if (newPreference === 'system') {
    localStorage.removeItem('theme');
  } else {
    localStorage.setItem('theme', newPreference);
  }
};

Usage

import { ThemeToggle } from '@/components/ThemeToggle';

// In your header or navbar
<ThemeToggle className="text-xl" />;

© 2026 All rights reserved.