A custom hook that persists state to localStorage with automatic serialization.
import { useState, useEffect } from class=class="text-emerald-400">"text-emerald-400">'react'
function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch {
return initialValue
}
})
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue))
} catch {
console.error(class=class="text-emerald-400">"text-emerald-400">'Failed to save to localStorage')
}
}, [key, storedValue])
return [storedValue, setStoredValue]
}
export default useLocalStorageImport and use like useState: const [name, setName] = useLocalStorage('user-name', 'Guest'). The value persists across page reloads automatically.
Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.