Managing Tasks with State
×


Managing Tasks with State

112

🧠 Managing Tasks with State in To-Do List App

In any To-Do List app, tasks are the core. You’ll need to store, update, mark as complete, and delete tasks — all driven by React's state system. Let’s break down how to manage tasks using useState in a clean and scalable way! 🛠️

📦 Initial State Setup

Start by defining your task list in a state variable using the useState hook. Each task can be an object with id, text, and done fields:

const [tasks, setTasks] = useState([
  { id: 1, text: "Learn React", done: false },
  { id: 2, text: "Build a To-Do app", done: true },
]);

This state holds all your tasks. You’ll update it as users add, complete, or remove items. ✅

➕ Adding a New Task

To add a task, create a handler function that pushes a new task object into the tasks array:

const addTask = (text) => {
  const newTask = {
    id: Date.now(),
    text,
    done: false,
  };
  setTasks([...tasks, newTask]);
};

📌 Always spread the old array and add the new item to avoid mutating state directly.

✅ Toggling Task Completion

To mark a task as complete or undo it, toggle its done field:

const toggleTask = (id) => {
  const updatedTasks = tasks.map(task =>
    task.id === id ? { ...task, done: !task.done } : task
  );
  setTasks(updatedTasks);
};

🔁 This pattern ensures React re-renders with updated data efficiently.

❌ Deleting a Task

To remove a task, filter it out from the state:

const deleteTask = (id) => {
  const updatedTasks = tasks.filter(task => task.id !== id);
  setTasks(updatedTasks);
};

🔥 Simple, clean and non-mutative — the React way!

🧱 Full Example of Managing State

import React, { useState } from "react";

function TodoApp() {
  const [tasks, setTasks] = useState([]);

  const addTask = (text) => {
    setTasks([...tasks, { id: Date.now(), text, done: false }]);
  };

  const toggleTask = (id) => {
    setTasks(tasks.map(task =>
      task.id === id ? { ...task, done: !task.done } : task
    ));
  };

  const deleteTask = (id) => {
    setTasks(tasks.filter(task => task.id !== id));
  };

  return (
    <div>
      <h2>📝 To-Do List</h2>

      <button onClick={() => addTask("New Task")}>Add Task</button>

      <ul>
        {tasks.map(task => (
          <li key={task.id}>
            <span 
              style={{ textDecoration: task.done ? "line-through" : "none" }}
              onClick={() => toggleTask(task.id)}
            >
              {task.text}
            </span>

            <button onClick={() => deleteTask(task.id)}>❌</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

✨ This small app already lets you add, toggle, and delete tasks — all using useState efficiently!

🧠 Recap

  • 🧠 Use useState to store and update tasks
  • ➕ Add tasks using setTasks([...tasks, newItem])
  • ✅ Toggle tasks by mapping and updating
  • ❌ Delete tasks with filter()

Mastering state is the heart of building dynamic React apps — and a To-Do list is the perfect place to learn it! 🚀

🚀 What’s Next?

  • 🧠 Create a custom hook useTasks() to reuse logic
  • 💾 Store tasks in localStorage for persistence
  • 🧪 Add validation (e.g., no empty tasks)

Managing state cleanly means your UI will always reflect what’s really happening under the hood. Time to level up! 🔧



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat