#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Rendering Lists and Conditional Contents

Using Stateful List

A stateful list is an array stored in React state, so that adding, removing or editing an item automatically re-renders the list on screen. Static arrays defined in a file are fine for content that never changes, but anything the user interacts with, such as a to-do list, a shopping cart or a list of comments, needs to live in state with useState.

Putting the array in state

You create the state with an initial array, render it with map(), and change it only through the setter function. The key rule is that you never modify the existing array. Instead, you build a new array and pass that to the setter. React compares the old and new references; a new array tells it something changed.

import { useState } from 'react';

const initialTasks = [
  { id: 1, text: 'Revise closures', done: false },
  { id: 2, text: 'Practise flexbox', done: true }
];

function TaskList() {
  const [tasks, setTasks] = useState(initialTasks);
  const [draft, setDraft] = useState('');

  function addTask(event) {
    event.preventDefault();
    if (!draft.trim()) return;
    setTasks(prev => [...prev, { id: crypto.randomUUID(), text: draft.trim(), done: false }]);
    setDraft('');
  }

  function toggle(id) {
    setTasks(prev => prev.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
  }

  function remove(id) {
    setTasks(prev => prev.filter(t => t.id !== id));
  }

  return (
    <>
      <form onSubmit={addTask}>
        <input value={draft} onChange={e => setDraft(e.target.value)} />
        <button>Add</button>
      </form>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>
            <label>
              <input type="checkbox" checked={task.done} onChange={() => toggle(task.id)} />
              {task.text}
            </label>
            <button type="button" onClick={() => remove(task.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </>
  );
}

Immutable recipes for common changes

GoalAvoid (mutates)Use instead
Add to endpush[...prev, item]
Add to startunshift[item, ...prev]
Removespliceprev.filter(...)
Update one itemprev[i].done = trueprev.map(...) returning a copied object
Sort or reversesort, reversetoSorted, toReversed, or copy first

Newer array methods make some of these recipes easier. toSorted(), toReversed() and toSpliced() return changed copies instead of altering the original, and with(index, value) returns a copy with one position replaced. In environments without them, copy first with [...prev] and then call sort() on the copy.

Why the functional setter helps

Passing a function to the setter, as in setTasks(prev => ...), makes React give you the latest state. If two updates happen in the same event, or a handler was created during an earlier render, reading tasks directly might use an outdated array and lose an item. The functional form avoids that.

The push that does nothing

The classic mistake is tasks.push(newTask); setTasks(tasks);. The array has changed, but it is the same array object, so React sees an identical reference and may skip the re-render. Even when something else causes a render, mutating state leads to subtle bugs with memoised components. The same applies to objects inside the array: { ...t, done: !t.done } copies the object instead of editing it.

Also give each item a stable, unique ID when it is created, and use that as the key. Using the array index as a key breaks once items can be removed or reordered, because React may attach a checkbox state to the wrong row.

Finally, avoid storing values you can derive. The number of completed tasks, for instance, can be calculated with tasks.filter(t => t.done).length during rendering. Keeping it in a second state variable means remembering to update both every time, and they will eventually drift apart. Store the list once and compute counts, totals and filtered views from it.

Main points

Keep the array in state, replace it with a new array on every change, use filter, map and spread instead of mutating methods, and key items by stable IDs.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course