Nadeem Shareef

How to work with Arrays in ReactJS useState.

Hello Developers👋

ReactJS introduce Hooks in React 16.8. And since then the most used hook is "useState" || "useEffect"
In this blog, We will take a look at how work with Arrays and "useState" hook.

Table Of Contents

Adding a new value to Array

Let's first create a friends array we will have two properties, name, and age

const friendsArray = [
    {
        name: "John",
        age: 19,
    },
    {
        name: "Candy",
        age: 18,
    },
    {
        name: "mandy",
        age: 20,
    },
];
Enter fullscreen mode Exit fullscreen mode

Now let's work with this array and useState


import { useState } from "react";

const App = () => {
    const [friends, setFriends] = useState(friendsArray); // Setting default value

    const handleAddFriend = () => {
        ...
    };

    return (
        <main>
            <ul>
                // Mapping over array of friends
                {friends.map((friend, index) => (
                    // Setting "index" as key because name and age can be repeated, It will be better if you assign uniqe id as key
                    <li key={index}>
                        <span>name: {friend.name}</span>{" "}
                        <span>age: {friend.age}</span>
                    </li>
                ))}
                <button onClick={handleAddFriend}>Add Friends</button>
            </ul>
        </main>
    );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

const handleAddFriend = () => {
    setFriends((prevFriends) => [
        ...prevFriends,
        {
            name: "Random Friend Name",
            age: 20, // Random age
        },
    ]);
};

Enter fullscreen mode Exit fullscreen mode

Here, setState let us define an anonymous function that has its previews state as an argument to the function, then we are using spread operator to get our all previews value(state) now after this we can add our new value.

but this method only adds new value to the end of the array. And this brings me to our next topic

Updating a specific object in Array of objects

Let say you have an array of friends and you want to update the specific friend name || age.

Updating our friend's array


const friendsArray = [
    {
        id: 1,
        name: "handy",
        age: 19,
    },
    {
        id: 2,
        name: "Candy",
        age: 18,
    },
    {
        id: 3,
        name: "mandy",
        age: 20,
    },
];

Enter fullscreen mode Exit fullscreen mode
...
<button onClick={handleSecondFriend}>Change Second Name</button>
...
Enter fullscreen mode Exit fullscreen mode
    const handleSecondFriend = () => {
        setFriends(
            friends.map((friend) =>
                // Here you accept a id argument to the function and replace it with hard coded 🤪 2, to make it dynamic.
                friend.id === 2
                    ? { ...friend, name: "Changed Name" }
                    : { ...friend }
            )
        );
    };
Enter fullscreen mode Exit fullscreen mode

Adding a new value in two dimensional array(array in Array)

Let's update our array of friends again 😅
This time I am adding likes or hobbies also 🤪


const friendsArray = [
    {
        id: 1,
        name: "handy",
        age: 19,
        hobbies: ["Cooking", "Reading"],
    },
    {
        id: 2,
        name: "Candy",
        age: 18,
        hobbies: ["Bathing", "Eating"],
    },
    {
        id: 3,
        name: "mandy",
        age: 20,
        hobbies: ["Making Videos", "Dancing", "Coding"],
    },
];

Enter fullscreen mode Exit fullscreen mode

Now everything will be more interesting to work 🤩.
Let's display hobbies

    ...
    const [friends, setFriends] = useState(friendsArray);

    const handleThirdFriendHobby = () => {
        ...
    };

    return (
        <ul>
            {friends.map((friend) => (
                // I am no longer using index as key, as I have unique id value.
                <li key={friend.id}>
                    <span>name: {friend.name}</span>{" "}
                    <span>age: {friend.age}</span>
                    <br />
                    <span>Hobbies</span>
                    <ul>
                        {friend.hobbies.map((hobby) => (
                            <li>{hobby}</li>
                        ))}
                    </ul>
                </li>
            ))}
            <button onClick={handleThirdFriendHobby}>Add Hobby to mandy</button>
        </ul>
    );
    ...

Enter fullscreen mode Exit fullscreen mode

    const handleThirdFriendHobby = () => {
        setFriends(
            friends.map((friend) =>
                friend.id === 3
                    ? {
                          ...friend,
                          hobbies: [...friend.hobbies, "Random Hobby"],
                      }
                    : { ...friend }
            )
        );
    };

Enter fullscreen mode Exit fullscreen mode

Updating a specific object in two dimensional array(array in Array)

Let's update our array of friends again 😅
This time I am adding ids for hobbies 🤪


const friendsArray = [
    {
        id: 1,
        name: "handy",
        age: 19,
        hobbies: [
            { text: "Cooking", id: 1 },
            { text: "Reading", id: 2 },
        ],
    },
    {
        id: 2,
        name: "Candy",
        age: 18,
        hobbies: [
            { text: "Bathing", id: 1 },
            { text: "Eating", id: 2 },
        ],
    },
    {
        id: 3,
        name: "mandy",
        age: 20,
        hobbies: [
            { text: "Making Videos", id: 1 },
            { text: "Dancing", id: 2 },
            { text: "Coding", id: 3 },
        ],
    },
];

Enter fullscreen mode Exit fullscreen mode

    const handleFirstFriendHobby = () => {
        setFriends(
            friends.map((friend) =>
                friend.id === 1
                    ? {
                          ...friend,
                          hobbies: friend.hobbies.map((hobby) =>
                              // You can replace 2 with your dynamic value
                              hobby.id === 2
                                  ? { ...hobby, text: "Random Hobby" }
                                  : { ...hobby }
                          ),
                      }
                    : { ...friend }
            )
        );
    };

Enter fullscreen mode Exit fullscreen mode

Here we are mapping hobbies inside another mapping function, and you can replace the hard-coded 2 with dynamic value.

Closing here 👋👋👋

This is Shareef.
Live demo
GitHub repo of this blog
My Portfolio
Twitter ShareefBhai99
Linkedin
My other Blogs

Cover photo by Codevolution