ch-16 Update & Delete Array in React using useState

7 May 2024

ch-16 Update & Delete Array in React using useState

Managing arrays in React state often requires updating or deleting items. The useState hook, combined with the power of JavaScript array methods, allows for effective and efficient manipulation of array data in your components. In this guide, we'll explore how to update and delete items in an array stored in state.


Updating Items in an Array

To update items in an array within your state, you typically use the map method. This method creates a new array with the results of calling a provided function on every element in the calling array. Here’s how you can update an item in an array using useState.


Example Scenario

Imagine you have an array of tasks, each with a name and a status. You want to be able to update the status of a specific task.


Steps to Update an Item

  1. Initialize State: Start by setting up the initial state with an array of tasks.
  2. Create an Update Function: Define a function that updates the status of a specific task.
  3. Render and Update UI: Render the tasks and provide a way to trigger the update function.


Code Example

import React, { useState } from 'react';


const TaskUpdater = () => {

 const [tasks, setTasks] = useState([

  { id: 1, name: 'Task 1', completed: false },

  { id: 2, name: 'Task 2', completed: false },

  { id: 3, name: 'Task 3', completed: false }

 ]);


 const updateTask = (id) => {

  setTasks(tasks.map(task => 

   task.id === id ? { ...task, completed: !task.completed } : task

  ));

 };


 return (

  <div>

   <ul>

    {tasks.map(task => (

     <li key={task.id}>

      {task.name} - {task.completed ? 'Completed' : 'Pending'}

      <button onClick={() => updateTask(task.id)}>Toggle Status</button>

     </li>

    ))}

   </ul>

  </div>

 );

};


export default TaskUpdater;


In this example:

  • The tasks state is initialized with an array of task objects.
  • The updateTask function toggles the completed status of a task based on its id.
  • The tasks are rendered in a list, each with a button to toggle its status.


Deleting Items from an Array

To delete items from an array in state, you typically use the filter method. This method creates a new array with all elements that pass the test implemented by the provided function.


Example Scenario

Continuing with the task list example, you might want to remove a task from the array.


Steps to Delete an Item

  1. Initialize State: Use the same initial state as in the update example.
  2. Create a Delete Function: Define a function that removes a task by its id.
  3. Render and Delete UI: Render the tasks and provide a way to trigger the delete function.


Code Example

import React, { useState } from 'react';


const TaskDeleter = () => {

 const [tasks, setTasks] = useState([

  { id: 1, name: 'Task 1', completed: false },

  { id: 2, name: 'Task 2', completed: false },

  { id: 3, name: 'Task 3', completed: false }

 ]);


 const deleteTask = (id) => {

  setTasks(tasks.filter(task => task.id !== id));

 };


 return (

  <div>

   <ul>

    {tasks.map(task => (

     <li key={task.id}>

      {task.name} - {task.completed ? 'Completed' : 'Pending'}

      <button onClick={() => deleteTask(task.id)}>Delete</button>

     </li>

    ))}

   </ul>

  </div>

 );

};


export default TaskDeleter;


In this example:

  • The deleteTask function removes a task by its id using the filter method.
  • The tasks are rendered in a list, each with a button to delete the task.


Conclusion

Updating and deleting items in an array within React state is straightforward with the useState hook and JavaScript array methods like map and filter. These techniques allow you to efficiently manage dynamic arrays and ensure your state updates remain immutable and predictable. By mastering these methods, you can handle more complex state management scenarios in your React applications with ease.


Notes and Source Code