0 day streak
javascript / intermediate
Snippet

Custom Hook: useLocalStorage

This custom hook synchronizes a React state variable with the browser's localStorage, ensuring data persistence across page reloads.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
};
return [storedValue, setValue];
}
react
Breakdown
1
useState(() => { ... })
Lazy initialization to read from localStorage only once on mount.
2
JSON.parse(item)
Converts the stored string back into a JavaScript object/value.
3
window.localStorage.setItem(key, ...)
Updates the browser storage whenever the state changes.