TYPESCRIPT
import { useState, useEffect } from 'react'
export function useLocalStorage(key: string, initialValue: T) {
const [value, setValue] = useState(() => {
if (typeof window === 'undefined') return initialValue
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch {
return initialValue
}
})
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue] as const
} Usage
TYPESCRIPT
// Theme toggle
const [theme, setTheme] = useLocalStorage('theme', 'light')
// User preferences
const [user, setUser] = useLocalStorage('user', { name: '', email: '' })
// Shopping cart
const [cart, setCart] = useLocalStorage('cart', [])