useLocalStorage Local Storage Hook
Last updated: 2026-11-02
useLocalStorage Local Storage Hook
useLocalStorage keeps the reads and writes of useState in sync with localStorage: it reads the stored value lazily during initialization and writes back to disk on every update, so the state survives a page reload. It is the textbook example of a custom hook wrapping a native browser API. The returned setter behaves exactly like the one from useState, so callers never need to learn a second API just to get persistence for free.
| Group | Component Patterns |
|---|---|
| Kind | Hook |
| Since | React 16.8 |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key) // lazy init: read only once
return saved !== null ? JSON.parse(saved) : initial
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue]
}
⚙️ Parameters
| key | The storage key in localStorage; prefix it with your app name to avoid collisions. |
|---|---|
| initial | The value used when nothing is stored locally; any JSON-serializable type is supported. |
Returns:Returns a [value, setValue] tuple that works exactly like useState, except that reads and writes are persisted to localStorage automatically.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
Clicking the button increases the counter and writes it to localStorage; after a reload or reopening the page the count is still there, and "Reset" brings it back to zero.