typescriptbeginner
usePersistentState Hook
Like useState but persists to localStorage with JSON serialization and SSR safety.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect } from 'react';
export function usePersistentState<T>(key: string, defaultValue: T): [T, (value: T | ((prev: T) => T)) => void] {
const [state, setState] = useState<T>(() => {
if (typeof window === 'undefined') return defaultValue;
try {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : defaultValue;
} catch {
return defaultValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(state));
} catch { /* storage full or private mode */ }
}, [key, state]);
return [state, setState];
}
// Usage:
// const [filters, setFilters] = usePersistentState('search-filters', { sort: 'date' });Use Cases
- Persisting user preferences
- Form draft saving
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage
typescriptbeginner
usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
Best for: Detecting value changes
#hooks#state
typescriptintermediate
useFormValidation Hook
Lightweight form validation hook with field-level errors, touched tracking, and submit handling.
Best for: Contact forms
#hooks#forms
typescriptintermediate
useUndoRedo State History Hook
Add undo/redo capability to any state with history tracking, max size limits, and keyboard shortcuts.
Best for: Text editor undo/redo
#react#hooks