react js blog Binaryboxtuts

How To Modify State Arrays In ReactJS

Avatar photoPosted by

In React.js, you can modify arrays stored in the state when using the useState hook by following a similar approach as with class components. The key is to create a new copy of the array with the modifications and then update the state using the setState function returned by useState. Here’s how you can modify a state array in a functional component using the useState hook:

1. Initialize State

Initialize your state array using the useState hook. For example:

import React, { useState } from 'react';

function ArrayStateExample() {
  const [items, setItems] = useState([
        {id:1, name:'item 1'},
        {id:2, name:'item 2'},
        {id:3, name:'item 3'}
    ]);
  // ...
}

2. Modifying State

To modify the state array, create a new copy of the array with your changes and use the setItems function to update the state. Here are some common array modifications:

  • Adding an item to the array:
let newItem = {id:4, name:'item 4'}
setItems([...items, newItem ]);
  • Removing an item from the array:
let itemToRemove = 1
setItems(items.filter(item => item.id !== itemToRemove));
  • Updating an item in the array (for example, updating an item at a specific index):
let itemToUpdate = 1;
let newData = {id:1, name:'item 1 Updated'};
let updatedItems = [...items];
let index = updatedItems.findIndex(item => item.id === itemToUpdate);
if (index !== -1) {
    updatedItems[index] = newData;
    setItems(updatedItems);
}

Here is the complete code:

import { useEffect, useState } from 'react';

function ArrayStateExample() {
    const [items, setItems] = useState([
        {id:1, name:'item 1'},
        {id:2, name:'item 2'},
        {id:3, name:'item 3'}
    ]);

    useEffect(()=>{

        // add item
        let newItem = {id:4, name:'item 4'}
        setItems([...items, newItem ]);

        // update item
        let itemToUpdate = 1;
        let newData = {id:1, name:'item 1 Updated'};
        let updatedItems = [...items];
        let index = updatedItems.findIndex(item => item.id === itemToUpdate);
        if (index !== -1) {
            updatedItems[index] = newData;
            setItems(updatedItems);
        }

        // remove item
        let itemToRemove = 1
        setItems(items.filter(item => item.id !== itemToRemove));

    },[])

    return (
        <div></div>
    );
}

export default ArrayStateExample;

Just like with class components, it’s crucial to avoid direct mutations of the state. Always create a new copy of the array and set it as the state using the setItems function.

By following this pattern, you ensure that React’s state management works correctly, and your component will re-render when the state changes. This approach helps maintain the integrity of your component’s data and state throughout its lifecycle when using functional components with the useState hook.