Sub topic 13
Extracting a usePersistentState hook
This chapter assumes you have finished the previous chapter on saving to-dos in localStorage. You should know useState, useEffect, and how a useReducer result is used. Here you move the persistence code out of App and into a reusable custom hook.
Why extract a hook
The earlier chapter put two pieces of persistence code in App: a lazy initializer that reads localStorage, and an effect that writes back. That code has nothing to do with to-dos. It works for any value that can be turned into JSON.
A custom hook is a function whose name starts with use and that calls other hooks. Moving the code into one gives you three benefits:
Appreads as a description of the to-do app, not storage plumbing.- The same hook can store the filter, a theme, or any other setting.
- You can test and fix the storage logic in one place.
The hook
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:
useState(() => ...)is a lazy initializer. React calls the function only on the first render, solocalStorageis read once and not on every render.- The effect depends on
keyandvalue. It runs after the first render and after every change to either one. - The hook returns
[value, setValue], the same shape asuseState. Callers can swap one for the other.
Using it in App
Replace the useState call for the list with the hook. Nothing else in App changes.
import { usePersistentState } from "./usePersistentState";
export default function App() {
const [todos, setTodos] = usePersistentState("todos", []);
const [filter, setFilter] = usePersistentState("filter", "all");
// addTodo, toggleTodo, deleteTodo, and the JSX stay the same.
}Each call keeps its own state under its own key. Reload the page and both the list and the selected filter come back.
Common errors
- Corrupt data.
JSON.parsethrows if the saved text is not valid JSON, and the whole app crashes on load. Wrap the read intryandcatch, and returninitialValueon failure. - Changing
keyat runtime. The state does not reload from the new key. The effect only writes the current value under it. Keep keys constant, or give the component akeyprop so it remounts. - Values JSON cannot hold. Functions,
undefined, andDateobjects do not survive a round trip. Dates come back as strings. - Storage unavailable.
setItemcan throw when storage is full or blocked, such as in some private browsing modes.
A safer version of the reader:
function readStored(key, initialValue) {
try {
const saved = localStorage.getItem(key);
return saved !== null ? JSON.parse(saved) : initialValue;
} catch {
return initialValue;
}
}Pass it to the initializer with useState(() => readStored(key, initialValue)).
Exercise
The hook is called with the key "filter" and the initial value "all". The user selects "active" and reloads the page. Which value does useState start with after the reload, and why?
Show answer
It starts with "active". The lazy initializer runs on the first render of the reloaded page, finds the string "active" (stored as JSON) under the "filter" key, and parses it. The initial value "all" is used only when nothing is stored.
Exercise
Write the hook change that stops the app from crashing when localStorage contains invalid JSON for the key.
Show answer
Wrap the read in try and catch and return the initial value on failure, for example: useState(() => { try { const saved = localStorage.getItem(key); return saved !== null ? JSON.parse(saved) : initialValue; } catch { return initialValue; } }).