Thuta Learning
React
ProjectsWeb DevelopmentIntermediate

Project: Task Tracker Feature

ReactLesson 3040 min

What you'll walk away with

  • Build a controlled input bound to state and handle the form submit with preventDefault()
  • Add, toggle and delete tasks by returning new arrays with spread, map() and filter()
  • Pass functions from the state-owning parent to the child as callback props
  • Explain why the setTasks(prev => ...) updater form is the safer choice

Explain it simply

Explain it simply

In Part 1 the app was like a picture: you could only look at it. In Part 2 the user can type a new task, tick a checkbox to mark it done, and press Delete to remove it. The data shape ({id, text, done}) and the two components stay the same as in Part 1.

Think of a waiter and a kitchen. The waiter (TaskItem) never cooks; they just carry the order to the kitchen (TaskTracker). In React, carrying the order means calling a callback function the parent handed down. Data flows down, and events flow back up.

Problem → Why → Solution

The problem: you click, but the screen does not change

Here is a first handleSubmit written with everyday JavaScript habits. It pushes the new task into the array and then calls setTasks with that same array. When you press Add, the whole page flashes and the text you typed is gone.

Two bugs are mixed together here. First, preventDefault() is never called, so the browser submits the form the old-fashioned way and reloads the page. Second, even after fixing the reload, the list often does not update: push() changed the very array React is holding, so what reaches setTasks is the same array as before.

TaskTracker.jsx (first try)
function handleSubmit(event) {
  // no event.preventDefault(): the browser reloads the page
  const newTask = { id: Date.now(), text, done: false };
  tasks.push(newTask); // changes the array React already holds
  setTasks(tasks);     // same array again, so React can skip the re-render
  setText("");
}

Why doesn't React see the change?

When you call a state setter, React compares the new value with the old one using Object.is. If the reference is the same, React assumes nothing changed and may skip the re-render. That is why you never edit an array or object in state; you build a new copy and hand that over.

Core concept: data down, events up

All three Part 2 features (add, toggle, delete) change the tasks state. TaskTracker owns that state, so the code that changes it must live in TaskTracker too. TaskItem only asks: "please toggle this task". We build it in five steps.

1. Make the input controlled

Add const [text, setText] = useState("") and wire value={text} and onChange to setText. Now state is the source of truth for what the input shows, and setText("") clears the box after a submit.

2. Take over the form submit

Instead of an onClick on the button, use <form onSubmit={handleSubmit}> so pressing Enter works too. The first line of handleSubmit must be event.preventDefault(), or the browser reloads the page. Then text.trim() rejects tasks made only of spaces.

3. Always return a new array

Adding uses [...prev, newTask], toggling uses map() and copies only the changed task with { ...task, done: !task.done }, and deleting uses filter(). All three return a new array and leave the original untouched.

4. Use the updater form

Write setTasks((prev) => [...prev, newTask]) instead of setTasks([...tasks, newTask]). prev is the latest state React has, so even two updates in a row never overwrite each other.

5. Hand the functions down as callback props

Wrap each call in an arrow function, onToggle={() => toggleTask(task.id)}, so TaskItem can call onToggle() without knowing the id and still change the right task. TaskItem keeps receiving text and done exactly as in Part 1 and only gains two callbacks.

ActionHow to write itWhat you get
Add[...prev, newTask]A new array, one item longer
Toggleprev.map(...)A new array with one task copied
Deleteprev.filter(...)A new array, one item shorter
Avoidpush, splice, task.done = xChanges the existing array in place

Run the code below in Node to see the difference between push and spread at the reference level. Notice too that map() reuses every task object it does not change.

immutable-updates.js
const tasks = [{ id: 1, text: "Learn React basics", done: true }];

// Wrong: push changes the existing array, then we hand back the same array
const pushed = tasks;
pushed.push({ id: 2, text: "Write tests", done: false });
console.log("after push, same array?", Object.is(tasks, pushed));

// Right: build a new array and leave the old one alone
const spread = [...tasks, { id: 3, text: "Deploy", done: false }];
console.log("after spread, same array?", Object.is(tasks, spread));
console.log("old length:", tasks.length, "new length:", spread.length);

// Toggling: copy only the task that changes
const toggled = spread.map((task) =>
  task.id === 2 ? { ...task, done: !task.done } : task,
);
console.log("task 1 reused:", toggled[0] === spread[0]);
console.log("task 2 copied:", toggled[1] !== spread[1], "done =", toggled[1].done);

// after push, same array? true
// after spread, same array? false
// old length: 2 new length: 3
// task 1 reused: true
// task 2 copied: true done = true
Mental model: the child asks, the parent changes
  1. User clicks inside TaskItem
  2. TaskItem calls onToggle or onDelete
  3. Parent sets a brand-new array
  4. React re-renders the list

setTasks never appears inside TaskItem. Every line that changes state lives in the component that owns it.

General pattern

jsx
const [items, setItems] = useState(initialItems);

function addItem(newItem) { setItems((prev) => [...prev, newItem]); }
function updateItem(id, changes) {
  setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...changes } : it)));
}
function removeItem(id) { setItems((prev) => prev.filter((it) => it.id !== id)); }

<Child
  onUpdate={() => updateItem(item.id, change)}
  onRemove={() => removeItem(item.id)}
/>

The component that owns the list writes add, update and remove with the updater form, then passes them to the child as callbacks wrapped in arrow functions.

Part 2 code: add, toggle and delete

We keep editing the same two files from Part 1. TaskItem gains a checkbox, a Delete button and two callback props; TaskTracker gains setTasks, a text state and three handlers. The sample data and the "X of N done" counter stay as they were and now update by themselves whenever the state changes.

src/components (2 files)
// src/components/TaskItem.jsx
function TaskItem({ text, done, onToggle, onDelete }) {
  return (
    <li className={done ? "task-item done" : "task-item"}>
      <label>
        <input type="checkbox" checked={done} onChange={onToggle} />
        <span className="task-text">{text}</span>
      </label>
      <button type="button" onClick={onDelete} aria-label={`Delete ${text}`}>
        Delete
      </button>
    </li>
  );
}

export default TaskItem;

// src/components/TaskTracker.jsx
import { useState } from "react";
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 },
];

function TaskTracker() {
  const [tasks, setTasks] = useState(sampleTasks);
  const [text, setText] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    const trimmed = text.trim();
    if (!trimmed) return;
    const newTask = { id: Date.now(), text: trimmed, done: false };
    setTasks((prev) => [...prev, newTask]);
    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 doneCount = tasks.filter((task) => task.done).length;

  return (
    <section className="task-tracker">
      <h2>My Tasks</h2>
      <p>
        {doneCount} of {tasks.length} done
      </p>
      <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>
      <ul>
        {tasks.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

  1. Controlled input stateconst [text, setText] = useState("");

    This state holds the input's value. Every keystroke calls setText through onChange, and setText("") clears it after a submit.

  2. Stop the page reloadevent.preventDefault();

    Cancels the form's default submit, which would reload the page and wipe out all state.

  3. Append with the updater formsetTasks((prev) => [...prev, newTask]);

    Returns a new array that spreads prev and puts the new task last. The reference is new, so React re-renders.

  4. Copy only the toggled taskprev.map((task) => (task.id === id ? { ...task, done: !task.done } : task)),

    Replaces only the task with a matching id by a new object with done flipped; every other task object is reused as it is.

  5. Callback bound to one taskonToggle={() => toggleTask(task.id)}

    The arrow function remembers task.id, so TaskItem simply calls onToggle() with no arguments. Writing toggleTask(task.id) directly would run it during render.

  6. Checkbox wired to the callback<input type="checkbox" checked={done} onChange={onToggle} />

    A controlled checkbox whose checked value comes from the prop. Because it sits inside a <label>, clicking the task text toggles it too.

You should see
Type a task and press Add or Enter: the new task appears at the bottom of the list and the input clears. Typing only spaces adds nothing. Ticking a checkbox toggles the strikethrough, Delete removes that task, and the "X of N done" counter follows every change.
Flow of adding a task
  1. Each keystroke calls setText through onChange
  2. Enter or Add makes the form call handleSubmit
  3. preventDefault() blocks the page reload
  4. The text is trimmed and checked for emptiness
  5. setTasks queues a new array and React re-renders

Empty text

return early: nothing is added

Has text

new task appended, input cleared

Why the updater function is safer

The tasks variable inside your component is a snapshot of this render. If one event handler calls setTasks twice, React queues both updates and applies them after the handler finishes. With plain values, both updates start from the old snapshot, so the second one overwrites the first. With updaters, prev is passed along, so both survive.

The code below is a simplified model of that queue.

update-queue-model.js
// A tiny model of how React applies queued state updates after an event.
function applyQueue(current, queue) {
  return queue.reduce(
    (state, update) => (typeof update === "function" ? update(state) : update),
    current,
  );
}

const tasks = ["Learn React basics"]; // the snapshot this render saw

const withValues = applyQueue(tasks, [[...tasks, "Write tests"], [...tasks, "Deploy"]]);
console.log("values:  ", withValues);

const withUpdaters = applyQueue(tasks, [
  (prev) => [...prev, "Write tests"],
  (prev) => [...prev, "Deploy"],
]);
console.log("updaters:", withUpdaters);

// values:   [ 'Learn React basics', 'Deploy' ]
// updaters: [ 'Learn React basics', 'Write tests', 'Deploy' ]

About Date.now() ids

The form adds one task at a time, so Date.now() is good enough here, and because it keeps growing after a reload it will not clash with the saved data in Part 3. Apps that create many items at once can hit the same millisecond twice; use crypto.randomUUID() or an id from the server there.

In real projects

In real projects

The "data down, events up" shape shows up in every React app. The quantity buttons in a shopping cart, the like button on a comment, the toggle switches on a settings page: each one only calls a callback prop such as onChange or onRemove, while the page or a store owns the state. That is what lets one button component be reused in many places.

When items multiply and the handlers get crowded, teams often move this map/filter/spread logic into a reducer function used with useReducer. A reducer is just these update functions collected under action types, so being fluent with immutable updates here makes reducers, Redux Toolkit and Zustand much easier to pick up.

Common mistakes

Common mistakes

Mutating the state array with push or splice

Writing tasks.push() or task.done = true and then setTasks(tasks) keeps the same reference, so the screen often does not update. Worse, the change suddenly appears when something unrelated re-renders, which makes the bug hard to trace. Only ever set a new copy built with spread, map or filter.

Forgetting preventDefault()

The form's default submit reloads the page, so every task you added disappears, and the console logs vanish with it, hiding what happened. Make it the first line of handleSubmit.

Calling the callback during render

onDelete={deleteTask(task.id)} does not pass a function; it calls one while rendering. Every render then deletes tasks and changes state, which can end in a "Too many re-renders" error. Wrap it as () => deleteTask(task.id).

Mini challenge

Add rename and clear-completed

Write two more update functions for the Task Tracker as pure functions: renameTask(list, id, newText) changes a task's text, and clearCompleted(list) removes finished tasks. You can then use them in the component, for example setTasks((prev) => clearCompleted(prev)).

  • Both functions return a new array and never modify the input array or its task objects
  • renameTask trims newText and returns the list unchanged (same reference) when the result is empty
  • renameTask copies only the task whose id matches
  • Print the results and show that the original list still has three tasks
task-updates.js
const tasks = [
  // TODO: three tasks with id, text and done (make at least one done)
];

function renameTask(list, id, newText) {
  // TODO: trim newText; if it is empty, return list itself
  // TODO: otherwise map over list and copy only the matching task
}

function clearCompleted(list) {
  // TODO: keep only the tasks that are not done
}

// TODO: rename task 2, try a blank rename, clear completed, print each result

Expected: The renamed list (task 2 reads "Build the Task Tracker"), true for the blank rename, a cleared list containing only task 2, and "original still has 3 tasks".

Show hint

renameTask has the same shape as toggleTask; use { ...task, text }. To check the blank case, print renameTask(tasks, 2, " ") === tasks.

Show solution
task-updates.js
const tasks = [
  { id: 1, text: "Learn React basics", done: true },
  { id: 2, text: "Build Task Tracker project", done: false },
  { id: 3, text: "Add filtering feature", done: true },
];

function renameTask(list, id, newText) {
  const text = newText.trim();
  if (!text) return list;
  return list.map((task) => (task.id === id ? { ...task, text } : task));
}

function clearCompleted(list) {
  return list.filter((task) => !task.done);
}

function show(label, list) {
  const lines = list.map(
    (task) => `${task.done ? "[x]" : "[ ]"} ${task.id} ${task.text}`,
  );
  console.log(`${label}\n  ${lines.join("\n  ")}`);
}

const renamed = renameTask(tasks, 2, "  Build the Task Tracker  ");
show("after rename:", renamed);
console.log("blank rename keeps same array:", renameTask(tasks, 2, "   ") === tasks);

const cleared = clearCompleted(renamed);
show("after clear completed:", cleared);
console.log("original still has", tasks.length, "tasks");

Quick quiz 1 / 3

What is the most likely result of tasks.push(newTask); setTasks(tasks);?

Quick quiz 2 / 3

Why does TaskTracker pass onDelete={() => deleteTask(task.id)} rather than onDelete={deleteTask(task.id)}?

Quick quiz 3 / 3

During a render where tasks is ["A"], a handler calls setTasks([...tasks, "B"]); setTasks([...tasks, "C"]);. What is tasks on the next render?

What to remember

  • Control the input with value and onChange, and call preventDefault() in the form's onSubmit
  • Never edit the state array; set a new one built with spread, map or filter
  • The parent that owns state passes functions down as callback props; the child only calls them
  • When an update depends on the previous state, use the setTasks((prev) => ...) updater form

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Project: Task Tracker Feature | Thuta Learning