Best Way to Store Todo Values in State & Adding Button to Check/Uncheck

Best Way to Store Todo Values in State & Adding Button to Check/Uncheck

In this guide, we will explore the most efficient way to store Todo values in React state and implement a button to check/uncheck tasks for better task management.

Key Features

- Efficient state management for todos.
- Add, edit, and delete tasks.
- Mark tasks as completed or uncompleted using a button.
- Store tasks in local storage for persistence.
- Display a real-time digital clock showing the current date and time.
- Clear all tasks with a single button.

Installation and Setup

    
// Create a new React project
npx create-react-app todo-app
cd todo-app
npm start
    
  

Todo List Component with Check/Uncheck Button

    
import React, { useState, useEffect } from "react";

function TodoApp() {
  const [tasks, setTasks] = useState([]);
  const [newTask, setNewTask] = useState("");
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const storedTasks = JSON.parse(localStorage.getItem("tasks")) || [];
    setTasks(storedTasks);
  }, []);

  useEffect(() => {
    localStorage.setItem("tasks", JSON.stringify(tasks));
  }, [tasks]);

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  const addTask = () => {
    if (newTask.trim() === "") return;
    setTasks([...tasks, { text: newTask, completed: false }]);
    setNewTask("");
  };

  const toggleTask = (index) => {
    const updatedTasks = tasks.map((task, i) =>
      i === index ? { ...task, completed: !task.completed } : task
    );
    setTasks(updatedTasks);
  };

  const clearTasks = () => {
    setTasks([]);
    localStorage.removeItem("tasks");
  };

  return (
    

Todo List

Current Time: {currentTime.toLocaleTimeString()}

setNewTask(e.target.value)} className="border p-2 w-full mb-2" />
    {tasks.map((task, index) => (
  • {task.text}
  • ))}
); } export default TodoApp;

Best Practices for Managing State

- Use objects in state to track task properties like completion status.
- Avoid directly mutating state; always create a new array or object.
- Store persistent data in local storage for better user experience.
- Optimize UI with proper event handling and visual feedback.