How to work with Arrays in ReactJS useState.
Tags: react, webdev, array, usestate
Published: 2021-05-21 08:00:44

# **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](#adding-new-value-to-array)
* [Updating a specific object in Array of objects](#chapter-2)
* [Adding a new value in two dimensional array(array in Array)](#array-in-array)
* [Updating a specific object in two dimensional array(array in Array)](#array-in-array-2)

### Adding a new value to Array <a name="adding-new-value-to-array"></a>

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

```js
const friendsArray = [
    {
        name: "John",
        age: 19,
    },
    {
        name: "Candy",
        age: 18,
    },
    {
        name: "mandy",
        age: 20,
    },
];
```
Now let's work with this **array** and **useState**

```jsx

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;

```

* Here, we are mapping over friends array and displaying it.
* Let's now see *How to add new values to this array*

```js 

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

```

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 <a name="chapter-2"></a>

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

> Updating our friend's array

```js

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

```

* Now we have a unique id to update only one specific object
* Add a button.

```html
...
<button onClick={handleSecondFriend}>Change Second Name</button>
...
```

* Here I am targeting only a second friend name but you can how every change it to target dynamic value(id).
* Let's work on **handleSecondFriend* function.

```js
    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 }
            )
        );
    };
```

* Here we are changing the object that matches the id or the hardcoded value **'2'**

### Adding a new value in two dimensional array(array in Array) <a name="array-in-array"></a>

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

```js

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"],
    },
];

```

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

```jsx
    ...
    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>
    );
    ...

```

* Now let's add || modify **3rd** friend hobby.

```js

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

```

* How easy and interesting it was, but as previews, this only adds a new hobby to the end of the array, and this brings us to our next topic.

### Updating a specific object in two dimensional array(array in Array) <a name="array-in-array-2"></a>

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

```js

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 },
        ],
    },
];

```

* Displaying the hobbies is as same as [previews](#array-in-array)
* Let's change the second hobby of the first friend(handy).

```js

    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 }
            )
        );
    };

```

> 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](https://blogs-rho.vercel.app/)
> [GitHub repo of this blog](https://github.com/shareef99/blogs/tree/master/array-and-usestate)
> My [Portfolio](https://portfolio.shareef.vercel.app/)
> Twitter [ShareefBhai99](https://twitter.com/shareefBhai99)
> [Linkedin](https://www.linkedin.com/in/nadeem-shareef-7a8394182/)
> My [other Blogs](https://dev.to/shareef)


> Cover photo by [Codevolution] (https://www.youtube.com/channel/UC80PWRj_ZU8Zu0HSMNVwKWw)