Why we need state
Our To-Do app shows tasks, but you can't add any: they're typed into the code. A normal variable won't help, because a component function runs again every time React redraws it, so normal variables start over each time. State is React's memory: it survives between redraws, and changing it tells React to update the screen.
The smallest example: a counter
import { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0); // a value React remembers, starting at 0
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}- 1
1οΈβ£
First render
useState(0) β count is 0. The button says "Clicked 0 times".
- 2
π±οΈ
You click
onClick runs setCount(count + 1), which asks React to change count to 1.
- 3
π
React re-renders
Counter runs again, useState now returns 1, and the button says "Clicked 1 times".
Events you'll use most
| Event | Fires when | To-Do example |
|---|---|---|
| onClick | Something is clicked | The delete button |
| onChange | An input's value changes | Typing in the task box, ticking a checkbox |
| onSubmit | A form is submitted (button or Enter) | Adding a task |
Step 1: The task form (a controlled input)
Create src/components/TaskForm.tsx. The text in the box lives in state, so React always knows it. This is called a controlled input.
import { useState } from "react";
type Props = {
onAdd: (title: string) => void;
};
// A text box and a button. The box's text lives in state (a "controlled input").
export function TaskForm({ onAdd }: Props) {
const [title, setTitle] = useState("");
return (
<form
className="task-form"
onSubmit={(e) => {
e.preventDefault(); // stop the browser from reloading the page
if (!title.trim()) return; // ignore empty tasks
onAdd(title.trim());
setTitle(""); // clear the box
}}
>
<input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="What do you need to do?" />
<button type="submit">Add</button>
</form>
);
}value={title}shows what's in state;onChangeupdates state on every key press.e.preventDefault()stops the browser's default form behaviour, which reloads the page.- TaskForm doesn't own the list. It just calls
onAdd(title), a function its parent gives it.
Step 2: Keep the list in App's state
The list of tasks belongs to App, because several components will need it. Replace src/App.tsx:
import { useState } from "react";
import type { Task } from "./types";
import { TaskForm } from "./components/TaskForm";
export default function App() {
const [tasks, setTasks] = useState<Task[]>([]);
function addTask(title: string) {
// Never change the old array. Make a new one with the new task at the end.
setTasks([...tasks, { id: Date.now(), title, done: false }]);
}
return (
<main className="app">
<h1>My To-Do List</h1>
<TaskForm onAdd={addTask} />
<p>You have {tasks.length} tasks.</p>
</main>
);
}Type a task and press Enter. βYou have 1 tasksβ becomes 2, 3β¦ Data flows down as props (onAdd), and actions flow up by calling functions.
Copying arrays and objects: the cheat sheet
// Add an item
setTasks([...tasks, newTask]);
// Remove an item
setTasks(tasks.filter((t) => t.id !== id));
// Change one item
setTasks(tasks.map((t) => (t.id === id ? { ...t, done: true } : t)));
// Change one field of an object
setUser({ ...user, name: "Asha" });You'll use the remove and change patterns in the next lesson.
Key takeaways
- βState is a component's memory; its setter triggers a re-render.
- βEvent handlers (onClick, onChange, onSubmit) are where state usually changes.
- βA controlled input keeps its text in state.
- βAlways replace state with new arrays and objects instead of changing them.
- βOur To-Do app can now add tasks typed by the user.
Frequently asked questions
What is useState in React?
useState is a hook that gives a component a value it remembers between renders, plus a function to change it: const [count, setCount] = useState(0). Calling the setter tells React to redraw the component with the new value.
Why can't I just change a normal variable?
A normal variable resets every time the component runs, and changing it doesn't tell React to update the screen. State survives between renders and triggers an update when you call its setter.
Why not tasks.push(newTask)?
push changes the existing array, and React compares old and new values to decide what to redraw. If it's the same array, React may not notice. Always create a new array: setTasks([...tasks, newTask]).
What is a controlled input?
An input whose text lives in React state: value={title} and onChange={(e) => setTitle(e.target.value)}. React is always the single source of truth, so you can read, clear or check the text easily.
Why does my console log show the old value right after setState?
Setting state schedules a re-render; the new value appears the next time the component runs, not on the very next line. Use the new value you computed instead of reading state again.
π§ Quick check: state and events
1. What does useState(0) give you?
2. Which line correctly adds a task?
3. Why call e.preventDefault() in onSubmit?
4. How does the child TaskForm add a task to App's list?
Checking your accessβ¦