useLocalStorage
A hook for persisting state in localStorage with type safety. This custom hook provides a convenient way to persist state across page refreshes while maintaining type safety.
Implementation
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue] as const;
}
Usage
Store and retrieve a simple value
type Theme = 'light' | 'dark';
export default function App() {
const [theme, setTheme] = useLocalStorage<Theme>('theme', 'light');
const toggleTheme = () => {
setTheme(currentTheme => currentTheme === 'light' ? 'dark' : 'light');
};
return (
<div style={{
padding: '20px',
backgroundColor: theme= 'light' ? '#ffffff' : '#333333',
color: theme= 'light' ? '#333333' : '#ffffff',
minHeight: '100vh',
transition: 'all 0.3s ease'
}}>
<h1>Theme Switcher</h1>
<p>Current theme: {theme}</p>
<p>This preference will persist even after you refresh the page!</p>
<button
onClick={toggleTheme}
style={{
padding: '10px 20px',
backgroundColor: theme= 'light' ? '#333333' : '#ffffff',
color: theme= 'light' ? '#ffffff' : '#333333',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Switch to {theme === 'light' ? 'dark' : 'light'} theme
</button>
</div>
);
};
Parameters
keystringrequired
The key to store the value under in localStorage
initialValueTrequired
The initial value to use if no value is stored
Live Playground
Best Practices
- Use unique keys to avoid conflicts
- Handle errors appropriately
Performance Considerations
- localStorage operations are synchronous and can block the main thread
- Large objects should be stored with caution