Explain it simply
Explain it simply
After Part 2 you can add tasks, but a browser refresh takes you straight back to the three sample tasks. State lives only in memory, so it disappears when the page goes away. In this Part 3 we polish the app from a demo into a tool you could use every day.
Think of a notebook. Part 2's state is like writing on a whiteboard: wipe it and it is gone. localStorage is copying it into the notebook, and next time you open the app it reads the notebook back. We wrap that copy-and-read logic in a custom hook called useLocalStorage, then add filter buttons and useMemo.
Problem → Why → Solution
The problem: dropping localStorage straight into the component
Here is a first draft that tries to fix the refresh problem quickly. For a first-time visitor getItem returns null, JSON.parse(null) also returns null, and tasks.filter throws a TypeError that leaves a blank white screen.
Even after fixing that, setItem is called without JSON.stringify, so storage receives the text "[object Object],[object Object]". On the next visit JSON.parse throws a SyntaxError and the whole app breaks again. And because setItem sits in the component body, it runs on every single render.
function TaskTracker() {
// first visit: getItem returns null, so tasks is null and .filter crashes
const [tasks, setTasks] = useState(JSON.parse(localStorage.getItem("tasks")));
// runs on every render and stores "[object Object],[object Object]"
localStorage.setItem("tasks", tasks);
const doneCount = tasks.filter((task) => task.done).length;
// ...
}Why does this break?
localStorage is an external system owned by the browser. It stores only strings, returns null when nothing is there, and may hold corrupted data. Code that syncs with an external system belongs in an effect, not in render, and the code that reads it must expect null and broken JSON.
Core concept: a custom hook, a derived list and useMemo
Part 3 adds three pieces: a hook that saves the data, a filter state, and the code that computes the visible list. The data shape ({id, text, done}) and Part 2's three handlers do not change by a single character. Getting persistence just by swapping useState for useLocalStorage is exactly what a custom hook is good for.
1. Give the hook the same API as useState
useLocalStorage(key, initialValue) returns [value, setValue], so TaskTracker keeps using its setTasks((prev) => ...) updaters unchanged. Starting the name with "use" tells React and the linter that this function is a hook and must follow the rules of hooks.
2. Read once with a lazy initializer
Passing a function, useState(() => readStored(key, initialValue)), means storage is read only on the first render. readStored returns the fallback for null and catches JSON.parse errors.
3. Write inside an effect
useEffect runs after render and again only when [key, value] changes. JSON.stringify(value) turns the array into a string before saving. StrictMode may run the effect twice in development, which is harmless because it writes the same value again.
4. Keep the filter as state and the list as derived
Only the user's choice ("all", "active" or "done") goes into state. The filtered list is never stored; it is computed from tasks and filter, so toggling a task keeps the list correct automatically.
5. Cache it with useMemo
useMemo(() => ..., [tasks, filter]) recalculates only when one of the two dependencies changes; a re-render caused by typing in the input reuses the previous result. Because Part 2 always set new arrays, every change to tasks gives a new reference that useMemo can notice.
// A stand-in for localStorage: like the real one, it stores strings only.
const store = new Map();
const storage = {
getItem: (key) => (store.has(key) ? store.get(key) : null),
setItem: (key, value) => store.set(key, String(value)),
};
const tasks = [
{ id: 1, text: "Learn React basics", done: true },
{ id: 2, text: "Build Task Tracker project", done: false },
];
storage.setItem("tasks", tasks); // forgot JSON.stringify
console.log("stored:", storage.getItem("tasks"));
try {
JSON.parse(storage.getItem("tasks"));
} catch (err) {
console.log("reading it back fails:", err.name);
}
storage.setItem("tasks", JSON.stringify(tasks));
const loaded = JSON.parse(storage.getItem("tasks"));
console.log("round trip:", loaded[1].text, "| done =", loaded[1].done);
console.log("missing key gives:", storage.getItem("nothing-here"));
// stored: [object Object],[object Object]
// reading it back fails: SyntaxError
// round trip: Build Task Tracker project | done = false
// missing key gives: null- First render: read storage once
- Handlers set a brand-new array
- The effect saves it as JSON
- useMemo derives the visible list
State is the source of truth and localStorage is only a copy of it. Never write to storage directly during render.
General pattern
function usePersistentState(key, fallback) {
const [value, setValue] = useState(() => loadFrom(key, fallback));
useEffect(() => { saveTo(key, value); }, [key, value]);
return [value, setValue];
}
const [items, setItems] = usePersistentState("items", []);
const [view, setView] = useState("all");
const shown = useMemo(() => selectItems(items, view), [items, view]);A persistent-state hook reads with a lazy initializer and writes in an effect. The view choice stays in its own state, and the displayed list is derived with a useMemo that lists both dependencies.
Part 3 code: persistence and filters
Create src/hooks/useLocalStorage.js; TaskTracker.jsx is shown in full. Compared with Part 2, useState(sampleTasks) became useLocalStorage("tasks", sampleTasks), and the filter state and buttons, visibleTasks, the "tasks left" counter and an empty message are new. TaskItem.jsx is exactly as in Part 2.
// src/hooks/useLocalStorage.js
import { useEffect, useState } from "react";
function readStored(key, fallback) {
try {
const saved = localStorage.getItem(key);
return saved === null ? fallback : JSON.parse(saved);
} catch {
return fallback; // corrupted JSON: start from the fallback
}
}
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => readStored(key, initialValue));
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
export default useLocalStorage;
// src/components/TaskTracker.jsx (TaskItem.jsx is unchanged from Part 2)
import { useMemo, useState } from "react";
import useLocalStorage from "../hooks/useLocalStorage";
import TaskItem from "./TaskItem";
const sampleTasks = [
{ id: 1, text: "Learn React basics", done: true },
{ id: 2, text: "Build Task Tracker project", done: false },
{ id: 3, text: "Add filtering feature", done: false },
];
const FILTERS = [
{ value: "all", label: "All" },
{ value: "active", label: "Active" },
{ value: "done", label: "Done" },
];
function TaskTracker() {
const [tasks, setTasks] = useLocalStorage("tasks", sampleTasks);
const [filter, setFilter] = useState("all");
const [text, setText] = useState("");
function handleSubmit(event) {
event.preventDefault();
const trimmed = text.trim();
if (!trimmed) return;
setTasks((prev) => [...prev, { id: Date.now(), text: trimmed, done: false }]);
setText("");
}
function toggleTask(id) {
setTasks((prev) =>
prev.map((task) => (task.id === id ? { ...task, done: !task.done } : task)),
);
}
function deleteTask(id) {
setTasks((prev) => prev.filter((task) => task.id !== id));
}
const visibleTasks = useMemo(() => {
if (filter === "active") return tasks.filter((task) => !task.done);
if (filter === "done") return tasks.filter((task) => task.done);
return tasks;
}, [tasks, filter]);
const remaining = tasks.filter((task) => !task.done).length;
return (
<section className="task-tracker">
<h2>My Tasks</h2>
<p>{remaining === 1 ? "1 task left" : `${remaining} tasks left`}</p>
<div className="filters" role="group" aria-label="Filter tasks">
{FILTERS.map(({ value, label }) => (
<button
key={value}
type="button"
aria-pressed={filter === value}
onClick={() => setFilter(value)}
>
{label}
</button>
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={text}
onChange={(event) => setText(event.target.value)}
placeholder="Add a new task..."
aria-label="New task"
/>
<button type="submit">Add</button>
</form>
{visibleTasks.length === 0 && <p className="empty">Nothing here yet.</p>}
<ul>
{visibleTasks.map((task) => (
<TaskItem
key={task.id}
text={task.text}
done={task.done}
onToggle={() => toggleTask(task.id)}
onDelete={() => deleteTask(task.id)}
/>
))}
</ul>
</section>
);
}
export default TaskTracker;Code breakdown
- Safe read with a fallback
return saved === null ? fallback : JSON.parse(saved);When the key does not exist yet (first visit) it returns the fallback; if the JSON is corrupted, JSON.parse throws and the catch block returns the fallback instead.
- Lazy initial state
const [value, setValue] = useState(() => readStored(key, initialValue));Because it is wrapped in an arrow function, readStored runs once at mount instead of reading and parsing storage on every render.
- Sync to storage after render
localStorage.setItem(key, JSON.stringify(value));Lives in the effect, so it runs after render and again whenever value changes. stringify stores real JSON instead of "[object Object]".
- One-line swap from Part 2
const [tasks, setTasks] = useLocalStorage("tasks", sampleTasks);The return shape matches useState, so persistence arrives without touching any handler.
- Memoized derived list
}, [tasks, filter]);The callback reads both tasks and filter, so both must be listed. Leave out filter and clicking the buttons no longer changes the list.
- Accessible toggle buttons
aria-pressed={filter === value}Announces the pressed state so screen-reader users know which filter is active, and lets CSS style the selected button with an [aria-pressed="true"] selector.
On the first visit you see the three sample tasks and "2 tasks left". Add, toggle or delete tasks and refresh: the list stays as you left it. Active shows only unfinished tasks, Done shows only finished ones, and the selected button has aria-pressed="true". When nothing matches, "Nothing here yet." appears.Do we really need useMemo here?
Honestly, filtering a list of a few hundred tasks is so fast that users would not notice any difference without useMemo. In this project useMemo is there to practise dependency arrays. In real code, measure with the React DevTools Profiler and add it only around calculations that are actually slow.
In projects with the React Compiler enabled, the compiler can add this kind of memoization automatically, so you write useMemo by hand far less often. Understanding dependencies is still essential, because useEffect relies on exactly the same idea.
What this hook does not handle
If the key changes while the component is mounted, the hook does not read the new key; it copies the current value into it, so keep the key fixed. Two open tabs can overwrite each other (the window storage event can address that). localStorage does not exist during server rendering, so use this hook only in the browser.
In real projects
In real projects
localStorage is widely used for data that is merely annoying to lose: form drafts, a theme choice, recently viewed items, a dismissed banner. Each origin gets only a few megabytes and every call is synchronous, so it is not meant for large data. Any script on the page can read it, so never store secrets such as tokens or passwords there.
In a task app shared by a whole team, the tasks live in a server database and localStorage is at most an offline cache. The filter usually goes into a URL search parameter such as ?filter=active, so a shared link opens the same view. Thanks to the custom-hook shape, replacing storage with an API later means editing one hook.
Common mistakes
Common mistakes
Forgetting JSON.stringify or JSON.parse
Passing the array straight to setItem stores the string "[object Object],..." and the data is lost. Using the string from getItem without parsing it makes tasks.map fail because a string has no map method. Always pair stringify on save with parse on load.
Leaving a dependency out of useMemo
Writing only [tasks] and forgetting filter means clicking Active changes nothing, until some task changes and the filter suddenly appears. List every value the callback reads, and keep the react-hooks/exhaustive-deps lint rule enabled.
Trusting whatever is in storage
A user may have edited the value in DevTools, or an older version of the app may have saved a different shape. Without try/catch, one JSON.parse error blanks the whole app. Provide a fallback, and add a shape check such as Array.isArray when it matters.
Mini challenge
A search box and a safer loader
You want to add a search box to the Task Tracker. Before touching the component, write the logic as three pure functions and test them in Node. loadTasks reads from a storage object and falls back on corrupted or wrongly shaped data; getVisibleTasks applies both the filter and a search query; remainingLabel produces the header text.
- Build an in-memory storage with getItem/setItem and pass it to loadTasks instead of localStorage
- loadTasks returns the fallback when the key is missing, the JSON is broken, or the value is not an array
- getVisibleTasks(tasks, filter, query) respects the filter and searches case-insensitively with a trimmed query
- remainingLabel returns "All done!", "1 task left" or "N tasks left" correctly
function createMemoryStorage(initial = {}) {
// TODO: keep strings in a Map; getItem returns null for a missing key
}
function loadTasks(storage, key, fallback) {
// TODO: missing key -> fallback; broken JSON -> fallback; not an array -> fallback
}
function getVisibleTasks(tasks, filter, query) {
// TODO: "active" hides done tasks, "done" hides open ones
// TODO: then keep tasks whose text includes the trimmed, lower-cased query
}
function remainingLabel(tasks) {
// TODO: "All done!" / "1 task left" / "N tasks left"
}
// TODO: storage with a good key, a broken key and a wrong-shape key; print resultsExpected: "loaded: 3 tasks", the one-task fallback for the broken, wrong-shape and missing keys, "active: 2,3", "all + 'TRACK': 2", "done + 'filter': (none)", and finally "2 tasks left", "1 task left" and "All done!".
Show hint
In loadTasks use try { ... } catch { return fallback; } and check Array.isArray(parsed) right after parsing. For search use task.text.toLowerCase().includes(q); an empty query matches everything, because every string includes "".
Show solution
function createMemoryStorage(initial = {}) {
const store = new Map(Object.entries(initial));
return {
getItem: (key) => (store.has(key) ? store.get(key) : null),
setItem: (key, value) => store.set(key, String(value)),
};
}
function loadTasks(storage, key, fallback) {
try {
const saved = storage.getItem(key);
if (saved === null) return fallback;
const parsed = JSON.parse(saved);
return Array.isArray(parsed) ? parsed : fallback;
} catch {
return fallback;
}
}
function getVisibleTasks(tasks, filter, query) {
const q = query.trim().toLowerCase();
return tasks.filter((task) => {
if (filter === "active" && task.done) return false;
if (filter === "done" && !task.done) return false;
return task.text.toLowerCase().includes(q);
});
}
function remainingLabel(tasks) {
const left = tasks.filter((task) => !task.done).length;
if (left === 0) return "All done!";
return left === 1 ? "1 task left" : `${left} tasks left`;
}
const fallback = [{ id: 1, text: "Learn React basics", done: true }];
const saved = [
{ id: 1, text: "Learn React basics", done: true },
{ id: 2, text: "Build Task Tracker project", done: false },
{ id: 3, text: "Add filtering feature", done: false },
];
const storage = createMemoryStorage({
tasks: JSON.stringify(saved),
broken: "{not json",
wrongShape: JSON.stringify({ id: 1 }),
});
const tasks = loadTasks(storage, "tasks", fallback);
console.log("loaded:", tasks.length, "tasks");
for (const key of ["broken", "wrongShape", "missing"]) {
const result = loadTasks(storage, key, fallback);
console.log(`${key} -> ${result.length} task (fallback)`);
}
const show = (list) => list.map((task) => task.id).join(",") || "(none)";
console.log("active:", show(getVisibleTasks(tasks, "active", "")));
console.log("all + 'TRACK':", show(getVisibleTasks(tasks, "all", "TRACK")));
console.log("done + 'filter':", show(getVisibleTasks(tasks, "done", "filter")));
console.log(remainingLabel(tasks));
console.log(remainingLabel(tasks.slice(0, 2)));
console.log(remainingLabel(fallback));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- useLocalStorage returns [value, setValue] like useState, so persistence arrives without changing any handler
- Read storage once with a lazy initializer and write it inside an effect with JSON.stringify
- Guard against null and corrupted JSON with a fallback; never assume storage is valid
- Keep the filter in state, derive the visible list, and list every value useMemo reads as a dependency
React Documentation — React