usestate add to array code example
Example 1: React Hooks append state
setTheArray(currentArray => [...currentArray, newElement])
Example 2: usestate array push
setTheArray([...theArray, newElement]);
Example 3: How to add object in an array using useState
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 (
useState with an array in React Hooks - Clue Mediator
{JSON.stringify(items, null, 2)}
);
}
export default App;
Example 4: functional component how to add to existing array react
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray([...theArray, `Entry ${theArray.length}`]);
};
return [
,
{theArray.map(entry =>
{entry}
)}
];
}
ReactDOM.render(
,
document.getElementById("root")
);
Example 5: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [...state, newMessage])
Example 6: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])