React
useLocalStorage
Learn to write a hook that syncs state to browser localStorage.
useLocalStorage
useLocalStorage stores a state in the browser's localStorage. The value survives page reload. It's a persistent version of useState.
The skeleton: const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; });. The initial value is given as a function; so localStorage is only touched on first read.
To save changes, add a useEffect: useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [value, key]);. So every change auto-saves.
JSON conversion
localStorage stores only strings. So to save objects or arrays, we convert to a string with JSON.stringify on write and back to an object with JSON.parse on read.
Error handling matters: a corrupted string can crash JSON.parse. So reads usually go inside a try/catch. Otherwise the app may crash on startup.
For type safety, one precaution: validate saved data against a shape. We keep it simple here, but in production this step is essential.
Exercise useLocalStorage skeleton
Complete the skeleton. Write a useLocalStorage(key, initial) hook. Use useState with lazy init: () => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; }. Add useEffect to call localStorage.setItem(key, JSON.stringify(value)); dependency [key, value]. Return [value, setValue]. Export the hook.
Show example solution
import { useState, useEffect } from "react";
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initial;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
export default useLocalStorage;
Test yourself
-
What does lazy init do?
- Reads every render
- Touches localStorage only on first read
- Skips useEffect
- Deletes state
Show answer
Touches localStorage only on first read — Lazy init only runs on first read.
-
Save method
To save to the browser, call ____.
Show answer
To save to the browser, call localStorage.setItem.
-
Match the useLocalStorage steps
- useState
- Lazy init
- localStorage.getItem
- Read
- JSON.parse
- String to object
- useEffect
- Save
Next lesson: useFetch