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.
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
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.
npx create-react-app usestate-with-array-react-hooks
The following article will help you to setup a startup 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.
import React, { useState } from 'react';
function App() {
const [items, setItems] = useState([]);
return (
<div class="App">
<h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
<br>
<button>Add More</button>
<br><br>
<label>Output:</label>
<pre>{JSON.stringify(items, null, 2)}</pre>
</div>
);
}
export default App;
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
import React, { useState } from 'react';
function App() {
const [items, setItems] = useState([]);
// handle click event of the button to add item
const addMoreItem = () => {
setItems(prevItems => [...prevItems, {
id: prevItems.length,
value: getRandomNumber()
}]);
}
// generate 6 digit random number
const getRandomNumber = () => {
return Math.random().toString().substring(2, 8);
}
return (
<div class="App">
<h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
<br>
<button onclick={addMoreItem}>Add More</button>
<br><br>
<label>Output:</label>
<pre>{JSON.stringify(items, null, 2)}</pre>
</div>
);
}
export default App;
4. Output
Run the application and check the output in the browser.
Output - useState with an array in React Hooks - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!