Learn the concept
Hooks
A useLocalStorage hook syncs React state with the browser's localStorage, providing a useState-like API that automatically persists values across page reloads. It handles JSON serialization, error recovery, SSR safety, and can synchronize across browser tabs via the storage event.
Why useLocalStorage:
Core Implementation Steps:
Error Handling:
JSON.parse can throw on malformed data — wrap in try/catchlocalStorage.setItem can throw QuotaExceededError — catch and optionally notifylocalStorage may not exist in SSR environments — check for windowSSR Safety:
typeof window !== 'undefined' before accessing localStorageCross-Tab Sync:
storage event fires when localStorage changes in another tabimport { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
// Lazy initialization: read from localStorage on first render
const [storedValue, setStoredValue] = useState(() => {
try {
const item = localStorage.getItem(key);
return item !== null ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key "${key}":`, error);
return initialValue;
}
});
// Write to localStorage whenever value changes
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.warn(`Error writing localStorage key "${key}":`, error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// Usage
function App() {
const [name, setName] = useLocalStorage('userName', '');
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
);
}Storing theme, language, sidebar state, and other UI preferences that should survive page reloads without requiring a backend
Automatically persisting form input as the user types so they don't lose progress if they accidentally close the tab
Keeping cart contents in localStorage so items persist when the user returns later, without requiring authentication
Build a developer tool that displays all localStorage keys, their sizes, lets you edit/delete them, and shows total storage usage with quota warnings
Create a todo application that stores all data in localStorage with useLocalStorage, supports cross-tab sync, and shows storage quota usage