Sub topic 12
Saving to-dos in localStorage
This chapter adds persistence to the to-do app. Reloading the page currently wipes the list, because React state lives in memory. You will save the list to the browser's localStorage and read it back on load.
I assume you have finished the earlier chapters. You should have todos state in App, immutable updates, and the useReducer refactor. You should also know useState and have seen useEffect briefly. The code uses useState for clarity. The same ideas apply when the state comes from useReducer.
What localStorage gives you
localStorage is a browser API that stores key-value pairs for one origin (scheme, host, and port). Data survives page reloads and browser restarts. It has four properties that shape the code:
- Values are always strings. Objects and arrays need
JSON.stringifyon the way in andJSON.parseon the way out. - The API is synchronous. Large values block the main thread, so keep stored data small.
- Storage is limited, usually to about 5 MB per origin.
setItemcan throw when the quota is full. - Users can clear it, edit it, or disable it. Your code cannot trust what it reads.
React does not know about localStorage. Reading or writing it is a side effect, meaning work that reaches outside the component's own render output. Rendering must stay pure, so this work goes in specific places.
Where reads and writes belong
Reads and writes go in different places.
| Operation | Where | Why |
|---|---|---|
| Read saved data | Lazy initializer passed to `useState` | Runs once, during the first render, so the first paint already has the saved list |
| Write data | `useEffect` | Runs after React commits the render, so rendering stays pure |
The lazy initializer is a function you pass to useState instead of a value. React calls it only on the first render and ignores it afterwards.
A first version
This version works but is fragile. Here is the idea in App:
import { useEffect, useState } from "react";
export default function App() {
const [todos, setTodos] = useState(() => {
const saved = localStorage.getItem("todos");
return saved !== null ? JSON.parse(saved) : [];
});
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);
// ...the rest of App is unchanged
}Try it. Add two tasks, reload the page, and the tasks come back. Open the browser's developer tools, go to the Application tab (Storage in Firefox), and look at localStorage. You will see a todos key holding a JSON string.
Why a lazy initializer
You could write useState(JSON.parse(localStorage.getItem("todos"))). That still works, but it reads and parses storage on every render, and React discards the result each time after the first. With a function, React runs the work once.
You could also start with [] and load the data in an effect. That causes a flash of an empty list, and it creates a bug described next.
The effect dependency array
The effect lists [todos], so it runs after the first render and after every render where todos changed identity. This is why immutable updates matter. If you mutated the array with push, the reference would stay the same, the dependency would look unchanged, and nothing would be saved.
The empty-list overwrite bug
Suppose you load saved data in an effect instead:
const [todos, setTodos] = useState([]);
useEffect(() => {
setTodos(JSON.parse(localStorage.getItem("todos") ?? "[]"));
}, []);
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);On the first render, todos is []. Effects run in order, so the second effect writes [] over your saved data before the first effect's setTodos takes effect. The saved list is gone. The lazy initializer avoids this because the correct value exists from the very first render.
Handling bad data
A real app must survive bad input. The stored string may be missing, corrupted, or from an older version of your app. JSON.parse throws on invalid JSON, and an uncaught error during render crashes the whole component tree. Writes can throw too, for example when the quota is full or when storage is disabled in a private window.
Wrap both operations in try/catch:
function loadTodos() {
try {
const saved = localStorage.getItem("todos");
if (saved === null) return [];
const parsed = JSON.parse(saved);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function saveTodos(todos) {
try {
localStorage.setItem("todos", JSON.stringify(todos));
} catch {
// Storage is full or unavailable. The app keeps working in memory.
}
}The Array.isArray check catches valid JSON of the wrong shape, such as {} or "hello". A stricter app would check each item for id, title, and done.
Using it with useReducer
After the reducer refactor, the same pattern applies. useReducer accepts an initializer as its third argument:
import { useEffect, useReducer } from "react";
function loadTodos() {
try {
const parsed = JSON.parse(localStorage.getItem("todos") ?? "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
export default function App() {
const [todos, dispatch] = useReducer(todosReducer, null, loadTodos);
useEffect(() => {
try {
localStorage.setItem("todos", JSON.stringify(todos));
} catch {
// Ignore write failures.
}
}, [todos]);
// ...
}The second argument is null because loadTodos needs no input. React calls loadTodos(null) once to build the initial state. The reducer itself stays pure and knows nothing about storage. That separation is the main reason to keep persistence in an effect.
Edge cases to know
- Strict Mode runs effects twice in development. React mounts, unmounts, and remounts each component to expose impure code. Our write is idempotent (writing the same value twice is harmless), so this is fine. Initializers also run twice in development, which is why they must be pure reads.
- Server rendering has no
localStorage. Frameworks that render on the server (such as Next.js) would throwReferenceError: localStorage is not defined. A Vite single-page app, as used in this tutorial, renders only in the browser, so you are safe. - Multiple tabs are not synced. Each tab holds its own state. If tab A saves a change, tab B still shows the old list and may overwrite A's change on its next save. The
storageevent fires in other tabs when storage changes, and you could listen for it. That is beyond this chapter. - Schema changes. If you later add a field to each to-do, old saved data lacks it. Either tolerate missing fields when reading, or store a version number alongside the data and migrate.
- Dates and special values.
JSON.stringifyturnsDateobjects into strings and dropsundefinedvalues and functions. Your to-do objects use only strings, booleans, and ids, so they round-trip exactly.
Checking your work
- Add three tasks and toggle one. Reload. The list and the toggled state should return.
- In developer tools, edit the
todosvalue tonot jsonand reload. The app should start with an empty list and not crash. - Set the value to
{"a":1}and reload. Again you should see an empty list. - Delete all tasks and reload. The list should stay empty, because the effect saved
[].
The next chapter pulls this load-and-save pair into a reusable usePersistentState hook, so any component can persist any value with one line.
Exercise
A teammate loads saved to-dos with useState([]) and a useEffect(..., []) that calls setTodos from localStorage. A second effect saves todos whenever it changes. After a reload, the saved list is always gone. Why does this happen, and how do you fix it?
Show answer
On the first render todos is [], and the save effect runs after that render and writes [] to localStorage, replacing the saved data before the loaded value is applied. Fix it by reading storage in a lazy initializer, useState(() => loadTodos()), so the first render already holds the saved list and the save effect writes back the same data.
Exercise
Why does the save effect need todos in its dependency array, and what would go wrong if you updated state by calling todos.push(item) and then setTodos(todos)?
Show answer
The dependency array tells React to rerun the effect when todos changes. React compares dependencies by reference. With push, the array keeps the same reference, so React sees no change, may skip the rerender, and does not rerun the effect, so the new item is never saved. Creating a new array, for example [...todos, item], gives a new reference and triggers both.
Exercise
Name two ways reading or writing localStorage can throw an error, and say how the code in this chapter handles each.
Show answer
JSON.parse throws when the stored string is not valid JSON, and setItem throws when the storage quota is full or storage is disabled. The code wraps the read in try/catch and returns [] on failure, and wraps the write in try/catch and ignores the failure so the app keeps working in memory.