Sub topic 13
Extracting a usePersistentState hook
In the previous chapter you saved to-dos to localStorage with a lazy initializer and an effect inside App. This chapter moves that logic into a reusable custom hook. It assumes you know useState, useEffect and its dependency array, and basic localStorage and JSON usage. It also assumes your App currently holds the persistence code inline.
Why extract a hook
The persistence code in App has two parts that belong together: reading the saved value on the first render, and writing it back when it changes. Nothing about those parts is specific to to-dos. If you also want to remember the selected filter, you would have to copy both parts again.
A custom hook is a JavaScript function whose name starts with use and that calls other hooks. It lets you share stateful logic, not state. Each component that calls the hook gets its own independent state, exactly as if you had written the useState and useEffect calls in that component.
The basic hook
Put this in src/usePersistentState.js:
import { useEffect, useState } from "react";
export function usePersistentState(key, initialValue) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved !== null ? JSON.parse(saved) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}Three details matter here.
- The initializer is a function.
useState(() => ...)runs the function only on the first render. PassinguseState(JSON.parse(localStorage.getItem(key)))would read storage on every render and throw away the result each time. - The return value matches
useState. Returning[value, setValue]means you can replace anyuseStatecall withusePersistentStateand change nothing else. Updater functions such assetValue(prev => ...)still work, becausesetValueis the real setter. - The effect depends on
[key, value]. It runs after a render in which either one changed, not on every render.
Using it in App
Replace the inline logic with one line:
import { usePersistentState } from "./usePersistentState";
export default function App() {
const [todos, setTodos] = usePersistentState("todos", []);
const [filter, setFilter] = usePersistentState("todos-filter", "all");
// ...the rest of App is unchanged
}Every setTodos call you wrote earlier for adding, toggling and deleting keeps working. The hook sits underneath them.
If you moved your state into useReducer earlier, the same idea applies, but the hook above wraps useState. You can either initialize the reducer from storage with a lazy third argument to useReducer, or write a second hook for reducers. For this app, keeping useState plus the hook is simpler.
What happens on each render
On first mount the effect writes back the value it just read. That write is redundant but harmless.
Hardening the hook
The basic hook breaks in three realistic situations.
- Corrupted data. If
localStorageholds text that is not valid JSON,JSON.parsethrows during render and the whole app crashes. This can happen if another script or an older version of your app wrote to the same key. - Blocked storage. Some browsers in private modes, or with strict privacy settings, throw on
localStorageaccess. Writes also throw when the storage quota is full. - No
window. If you later render on a server,localStoragedoes not exist.
A defensive version wraps storage access in try/catch and falls back to the initial value:
import { useEffect, useState } from "react";
function readValue(key, initialValue) {
try {
const saved = window.localStorage.getItem(key);
if (saved !== null) return JSON.parse(saved);
} catch {
// Storage is blocked or the saved text is not valid JSON.
}
return initialValue instanceof Function ? initialValue() : initialValue;
}
export function usePersistentState(key, initialValue) {
const [value, setValue] = useState(() => readValue(key, initialValue));
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch {
// Ignore write failures. The app still works, it just won't persist.
}
}, [key, value]);
return [value, setValue];
}The initialValue instanceof Function check mirrors how useState accepts either a value or a function. It lets callers pass an expensive initializer that only runs when nothing is saved.
Limits of the saved data
JSON.stringify only keeps JSON-compatible data. Your to-dos are plain objects with strings, booleans and numbers, so they round-trip cleanly. Other types do not:
| Value | After save and load |
|---|---|
| `Date` | A string, not a `Date` |
| `undefined` | Dropped from objects, `null` inside arrays |
| `Map`, `Set` | An empty object `{}` |
| Functions | Dropped |
Keep dates as ISO strings or timestamps in state, and convert when you display them.
Gotchas
Changing the key
The hook reads storage only once, on the first render. If key changes later, for example from todos-alice to todos-bob, the state still holds Alice's list, and the effect writes it under Bob's key. If you need per-key state, give the component a key prop so React remounts it:
<TodoApp key={userId} storageKey={`todos-${userId}`} />Remounting runs the initializer again with the new storage key.
Strict Mode double calls
In development, <StrictMode> runs initializers and effects twice to expose impure code. The hook survives this because reading is idempotent and writing the same value twice has no extra effect. Do not put side effects, such as generating IDs that you store, inside readValue.
Mutating the value
Persistence depends on React seeing a new reference. If you mutate the array with todos.push(...) and then call setTodos(todos), React sees the same reference and skips the re-render, so the effect never runs and nothing is saved. The immutable updates from earlier chapters are what make this hook work.
Several tabs
Two tabs of the app each hold their own state and overwrite the same key, so the last write wins. The browser fires a storage event in the other tabs when one tab changes a key. You can listen for it with window.addEventListener("storage", ...) and update state. That is optional for a to-do app, and it adds complexity, so add it only if you need live sync.
Rules of hooks
The hook follows the same rules as any hook. Call it at the top level of a component or another custom hook, never inside conditions or loops. The use prefix is not decoration, because linters use it to check these rules.
Testing the hook
You can test the hook without a component by using renderHook from React Testing Library. This example assumes a test runner with a DOM environment and global test, expect and beforeEach, such as Vitest with globals: true or Jest with jsdom:
import { act, renderHook } from "@testing-library/react";
import { usePersistentState } from "./usePersistentState";
beforeEach(() => {
localStorage.clear();
});
test("saves a value and restores it on the next mount", () => {
const first = renderHook(() => usePersistentState("todos", []));
act(() => {
first.result.current[1](["milk"]);
});
expect(JSON.parse(localStorage.getItem("todos"))).toEqual(["milk"]);
first.unmount();
const second = renderHook(() => usePersistentState("todos", []));
expect(second.result.current[0]).toEqual(["milk"]);
});
test("falls back to the initial value when saved text is invalid", () => {
localStorage.setItem("todos", "{not json");
const { result } = renderHook(() => usePersistentState("todos", ["default"]));
expect(result.current[0]).toEqual(["default"]);
});The second test needs the hardened version of the hook. With the basic version, it fails because JSON.parse throws.
Common errors
- The list resets on every reload. Check that you call
setTodosand not a plain variable, and that the key is the same string each time. Open the browser's Application tab and look under Local Storage to see what was written. Unexpected tokenin the console. Saved text is not valid JSON, often from an earlier experiment with the same key. Clear the key or use the hardened hook.- The saved value is
"[object Object]". Something wrote to the key withoutJSON.stringify. Always go through the hook for that key. - State is shared between two components. It is not. Each call creates separate state, so two components calling
usePersistentState("todos", [])hold two copies that only meet in storage. Share state by lifting it up or with context, as in the next chapter.
Exercise
You call usePersistentState("theme", "light") in two sibling components. One component calls setValue("dark"). Does the other component re-render with "dark" immediately? Why or why not?
Show answer
No. Each call to the hook creates its own useState, so the components have separate state. The first component's effect writes "dark" to localStorage, but the second component only reads storage once, in its initializer, so it keeps showing "light" until it remounts. To share the value, lift the state to a common parent, pass it down, or put it in context.
Exercise
Why does the hook pass a function to useState instead of calling localStorage.getItem directly in the argument?
Show answer
A direct call runs on every render, even though React only uses the result on the first one. Passing a function (a lazy initializer) makes React call it once, on mount, so storage is read and parsed only once.