useState array add item code example
Example 1: usestate array push
setTheArray([...theArray, newElement]);
Example 2: How to add object in an array using useState
import React, { useState } from 'react';
function App() {
const [items, setItems] = useState([]);
const addMoreItem = () => {
setItems(prevItems => [...prevItems, {
id: prevItems.length,
value: getRandomNumber()
}]);
}
const getRandomNumber = () => {
return Math.random().toString().substring(2, 8);
}
return (
<div classname="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;
Example 3: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])