Sub topic 12
Saving to-dos in localStorage
This chapter adds persistence so your to-dos survive a page refresh. It assumes you have the to-do app with useState or useReducer holding a todos array, and that you know what a React effect is at a basic level. Each chapter in this tutorial covers one concept, so the reusable hook comes later.
Why state disappears
React state lives in memory. When you reload the page, the app starts over and todos goes back to its initial value. The browser offers localStorage, a small key-value store that keeps strings across reloads for each site. It has two methods you need here: setItem(key, string) and getItem(key), which returns null if the key is missing.
Because localStorage stores only strings, you convert the array with JSON.stringify on the way in and JSON.parse on the way out.
Two steps: read once, write on change
Persistence has two parts:
- Load the saved data when the component first renders.
- Save the data each time it changes.
Loading with a lazy initializer
useState accepts a function as its initial value. React calls it only on the first render and ignores it afterward. This matters because reading and parsing storage on every render would be wasteful.
import { useEffect, useState } from "react";
function loadTodos() {
const saved = localStorage.getItem("todos");
return saved !== null ? JSON.parse(saved) : [];
}
export default function App() {
const [todos, setTodos] = useState(loadTodos);
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);
// ...form and list as before
}Pass loadTodos, not loadTodos(). Calling it in the argument runs the read on every render, even though React would discard the result.
Saving with an effect
Writing to localStorage is a side effect, meaning work that reaches outside React's rendering. Rendering must stay free of side effects, so the write goes in useEffect. The dependency array [todos] tells React to run the effect after any render in which todos has changed.
This is where the immutable updates from earlier chapters pay off. React compares todos by reference. Because map, filter, and spread create new arrays, the effect sees a change and saves. If you had mutated the array in place with push, the reference would stay the same and nothing would be saved.
Common errors
- Corrupted data crashes the app. If someone edits storage by hand,
JSON.parsethrows on invalid JSON. Wrap the read intry/catchand fall back to[]. - Storage unavailable. Private modes or full quotas can make
setItemthrow. Atry/catcharound the write keeps the app running. - Server rendering.
localStoragedoes not exist on the server. If you use a framework that renders there, read storage only in the browser. - Wrong key reuse. Two apps on the same origin sharing the key
"todos"overwrite each other. Use a specific key such as"react-todo-app:todos".
function loadTodos() {
try {
const saved = localStorage.getItem("todos");
return saved !== null ? JSON.parse(saved) : [];
} catch {
return [];
}
}Check your work
Add two to-dos, toggle one, and reload the page. Both should remain, with the toggle intact. To inspect the stored value, open your browser's developer tools, go to the Application tab (Storage in Firefox), and look under Local Storage.
Exercise
Why is useState(loadTodos) better than useState(loadTodos())?
Show answer
React calls a function passed to useState only on the first render. Writing loadTodos() runs the storage read and JSON parsing on every render, and React throws the result away after the first one.
Exercise
You change a to-do with todos[0].done = true; setTodos(todos);. After a reload, the change is missing. Why?
Show answer
The code mutates the existing array and passes the same reference to setTodos. React sees no change, so it does not re-render and the effect does not run, so nothing is written to storage. Create a new array and a new object instead, for example with map and spread.