Create reusable custom hooks to encapsulate complex logic and state management. The useTheme hook demonstrates how to manage theme state, persist preferences to localStorage, and apply CSS classes dynamically. Perfect for sharing functionality across components.
1import { useState, useEffect } from 'react';2 3const useTheme = () => {4 const [theme, setTheme] = useState<'light' | 'dark'>('light');5 6 useEffect(() => {7 const savedTheme = localStorage.getItem('theme') as 'light' | 'dark';8 if (savedTheme) {9 setTheme(savedTheme);10 }11 }, []);12 13 const toggleTheme = () => {14 const newTheme = theme === 'light' ? 'dark' : 'light';15 setTheme(newTheme);16 localStorage.setItem('theme', newTheme);17 document.documentElement.classList.toggle('dark');18 };19 20 return { theme, toggleTheme };21};1import { useTheme } from './useTheme';2 3const ThemeToggle = () => {4 const { theme, toggleTheme } = useTheme();5 6 return (7 <div className={cn("flex items-center gap-4", className)}>8 <span className="text-sm font-medium">9 Current theme: {theme}10 </span>11 12 <button onClick={toggleTheme}>13 Switch to {theme === 'light' ? 'Dark' : 'Light'}14 </button>15 </div>16 );17}Use your custom hook in any component to add theme switching functionality. The ThemeToggle component shows how to display the current theme, provide a toggle button, and render visual indicators. Clean separation between logic and presentation makes testing easier.