Problem 1: tasks vanish when you refresh
State lives in memory, so a refresh wipes it. The browser has a small storage box called localStorage that survives refreshes. We need to save tasks there whenever they change, and load them when the app starts.
The useEffect recipe
useEffect(() => {
// 1. do something outside React
return () => {
// 2. optional cleanup
};
}, [dependencies]); // 3. when to run again| Dependency array | When the effect runs | Example |
|---|---|---|
| [] | Once, after the first render | Fetch data when the page opens |
| [tasks] | After the first render, then whenever tasks changes | Save tasks to localStorage |
| (none) | After every render | Rarely what you want |
Step 1: Save and load tasks
Two small changes in App (shown in the full file below):
// Read saved tasks once, when the app starts.
function loadTasks(): Task[] {
const saved = localStorage.getItem("tasks");
return saved ? JSON.parse(saved) : [];
}
// Inside App:
const [tasks, setTasks] = useState<Task[]>(loadTasks);
// Save tasks every time they change.
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);localStorageonly stores text, so we turn the array into JSON text withJSON.stringifyand back withJSON.parse.useState(loadTasks)passes the function itself, so it runs only once at startup.- The effect has
[tasks]: every add, tick or delete saves automatically.
Add tasks, refresh the page: they're still there. We tested exactly this.
Problem 2: loading data from somewhere else
Real apps fetch data from a server. Let's practise with a small file: put this in public/tips.json. Vite serves files in public at the site's root, so it's available at /tips.json.
[
{ "text": "Do the hardest task first, while your energy is high." },
{ "text": "Break big tasks into small steps you can finish in 25 minutes." },
{ "text": "Write tomorrow's top 3 tasks before you stop for the day." }
]Step 2: Fetch with loading and error states
Any time you fetch, the screen has three possible states: loading, error, or success. Handle all three:
import { useEffect, useState } from "react";
type Tip = { text: string };
// Loads a tip from /tips.json once, and shows loading and error states.
export function TipOfTheDay() {
const [tip, setTip] = useState<Tip | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
let ignore = false; // if the component goes away before the answer arrives, ignore it
fetch("/tips.json")
.then((res) => {
if (!res.ok) throw new Error("Could not load tips");
return res.json();
})
.then((tips: Tip[]) => {
if (!ignore) setTip(tips[Math.floor(Math.random() * tips.length)]);
})
.catch(() => {
if (!ignore) setError("Could not load a tip right now.");
})
.finally(() => {
if (!ignore) setLoading(false);
});
return () => {
ignore = true; // cleanup
};
}, []); // [] = run once, when the component first appears
if (loading) return <p className="tip">Loading a tip…</p>;
if (error) return <p className="tip error">{error}</p>;
return <p className="tip">💡 {tip?.text}</p>;
}[]: fetch once, when the tip first appears.- Three pieces of state: the data,
loadinganderror, each shown with an early return. - Cleanup: if the component disappears before the answer arrives,
ignorestops us from updating a component that's gone.
The finished App (lessons 3–6)
import { useEffect, useState } from "react";
import type { Filter, Task } from "./types";
import { TaskForm } from "./components/TaskForm";
import { TaskList } from "./components/TaskList";
import { FilterBar } from "./components/FilterBar";
import { TipOfTheDay } from "./components/TipOfTheDay";
// Read saved tasks once, when the app starts.
function loadTasks(): Task[] {
const saved = localStorage.getItem("tasks");
return saved ? JSON.parse(saved) : [];
}
export default function App() {
const [tasks, setTasks] = useState<Task[]>(loadTasks);
const [filter, setFilter] = useState<Filter>("all");
// Save tasks every time they change.
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
function addTask(title: string) {
setTasks([...tasks, { id: Date.now(), title, done: false }]);
}
function toggleTask(id: number) {
setTasks(tasks.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function deleteTask(id: number) {
setTasks(tasks.filter((t) => t.id !== id));
}
// Worked out from state on every render. Not stored separately.
const visibleTasks = tasks.filter((t) => (filter === "active" ? !t.done : filter === "done" ? t.done : true));
const left = tasks.filter((t) => !t.done).length;
return (
<main className="app">
<h1>My To-Do List</h1>
<TaskForm onAdd={addTask} />
<FilterBar filter={filter} onChange={setFilter} />
<TaskList tasks={visibleTasks} onToggle={toggleTask} onDelete={deleteTask} />
<p className="count">
{left} {left === 1 ? "task" : "tasks"} left
</p>
<TipOfTheDay />
</main>
);
}Key takeaways
- ✓useEffect connects components to the outside world: storage, servers, timers.
- ✓The dependency array controls when the effect runs again.
- ✓Our tasks now survive a refresh thanks to localStorage.
- ✓Fetching data always needs loading and error states.
- ✓Next: replace localStorage with a real backend and add login.
Frequently asked questions
What is useEffect in simple words?
useEffect runs code after React has drawn the screen, for things outside React: saving to localStorage, fetching data, timers, changing the page title. The second argument (the dependency array) says when to run it again.
What does the empty array [] mean?
Run the effect once, after the component first appears. [tasks] means: run after the first render and again whenever tasks changes. No array at all means after every render, which you rarely want.
Why does my effect run twice in development?
StrictMode runs effects twice in development on purpose, to help you find missing cleanups. It doesn't happen in the built app. Our ignore flag makes the fetch safe either way.
Do I need useEffect to calculate values?
No. If it can be calculated from props or state while rendering, just calculate it. useEffect is only for talking to things outside React.
Why use a function in useState(loadTasks)?
Passing the function itself (not loadTasks()) tells React to call it only on the first render, so you don't read localStorage on every redraw.
🧠 Quick check: useEffect
1. When does useEffect(fn, []) run?
2. You want to save tasks whenever they change. Which dependency array?
3. What should a fetching component show while waiting?
4. What is the cleanup function for?
Checking your access…