useState with an array in React Hooks

Today we’ll show you how to use the useState with an array in React Hooks. In the previous article, we learned about the use of useState with object in React Hooks.

If you are new to React Hooks then check out the following articles from beginning.

useState Hook in React.

Let’s take a simple example to manage an array in the state variable.

useState with an array in React Hooks

  1. Create a react application
  2. Add HTML element to prepare UI
  3. Manage an array using useState
  4. Output

1. Create a react application

First, we’ll create a simple react application to implement the demo using create-react-app npm package. Run the following command to create a startup application.

The following article will help you to setup a startup application.

Create React Application

2. Add HTML element to prepare UI

In this small demo, we will handle the simple array in the state variable so let’s use a button element to add the new item in that array.

We have added the following code in the App.js component.

3. Manage an array using useState

Let’s write the logic to manage an array in the state variable. The handling of an array in the state variables using Hooks is very similar to the object. We have to manually merge the state by spreading an array.

In this example, we have used the previous state to update the state value. Check out the link below for more insight.

useState with the previous state in React Hooks

Here, we will push the id and 6 digits random generated value into the array. Look into the following article to generate the n-digit random number.

Generate an n-digit random number using JavaScript

Check out the following code to update an array in the state variable using Hooks.

App.js

4. Output

Run the application and check the output in the browser.

Output - useState with an array in React Hooks - Clue Mediator
Output – useState with an array in React Hooks – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

1 Response

  1. Masaya says:

    Was looking everywhere for this, thank you!!

Leave a Reply

Your email address will not be published. Required fields are marked *