React State, Events and Derived UI
Create a reliable task counter while understanding React re-renders, immutable updates and state derived from existing values.
Key Learning Objectives
- Explain why state updates trigger rendering.
- Use functional updates when a value depends on the previous value.
- Avoid mutating arrays in state.
- Derive completed counts without duplicate state.
UI is a function of current state
A React component describes what the interface should look like for its props and state. Calling a state setter schedules a new render; changing an ordinary local variable does not preserve a value across renders. If a button increments a counter multiple times in the same event, read the previous value through an updater function rather than closing over an outdated render snapshot. Keep event handlers as callbacks; never call an updater while rendering.
import { useState } from "react";
export function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(previous => previous + 1)}>
Completed: {count}
</button>;
}
The updater receives the latest queued value; React re-renders with the new count.
Update objects and arrays immutably
React compares references when deciding what has changed. Pushing into an existing state array and setting it back reuses the same reference and makes UI bugs more likely. Instead construct a new array using map, filter or spread. Keep a stable id on each task and use that id as the React key. An array index is unsafe when items can be inserted, removed or reordered, because it can attach component state to the wrong task.
setTasks(current => current.map(task =>
task.id === targetId ? { ...task, done: !task.done } : task
));
The array and the toggled object are new values; unchanged tasks retain their original objects.
Prefer derived values to duplicated state
If you already store the task list, you usually should not also store completedCount as separate state. That count can be calculated from tasks on every render. Separate copies of the same fact drift out of sync when developers forget to update both. For expensive derived calculations useMemo can help, but simple filters rarely need it. An effect is designed for synchronising with something outside React, such as a subscription; it is not necessary just to compute a value from props or state.
Build It: React weekly checklist
Build an interactive checklist with add, toggle, delete and completed-total features.
Project Deliverables
- Three reusable components with explicit props.
- State for tasks with stable ids.
- A derived completed count and an empty-state message.
Acceptance Criteria
- Toggling never mutates an existing task object.
- Deleting a task updates the total immediately.
- No console key warnings after reordering.
Next Steps & Related Learning
This interactive lesson is part of the React curriculum. Continue exploring or try another interactive lesson: