Last updated on October 27, 2022
Spread syntax plays a vital role in development. Working with react JS we can push an element into a state Array without using the JavaScript push() method.
The spread operator takes out the existing elements of the array and creates a new array after adding values. For example, we have an array of names and we need to add another name at the click of a button
import {useState} from 'react';
export default function App() {
const [users, setUsers] = useState(['Jackson', 'Robbert']);
const handleClick = () => {
// 👇️ push to end of state array
setUsers(current => [...current, 'Carl']);
};
return (
<div>
<div>
<button onClick={handleClick}>Push to state array</button>
</div>
{names.map((element, index) => {
return (
<div key={index}>
<h2>{element}</h2>
</div>
);
})}
</div>
);
}
In this example, we used react useState hook, obviously a function-based component. In this example, we are adding a name in the state array.
const [users, setUsers] = useState(['Jackson', 'Robbert']);
We already have two names in the state array and need to add another name.
// 👇️ push to end of state array
setUsers(current => [...current, 'Jhon']);
Adding a new value in the state array we used the setUsers function which will be updated to state on the click event.
We pass a ‘current’ argument into the setUsers method, the current argument has an updated state array.
Next, we used the spread operator to add a new name to the state array, as the mentioned start of the article spread operator takes out the current values and builds a new array with the addition of a new value.
In case of adding a new value at the start of the array, we need to follow the below code
setUsers(current => ['Zoey', ...current]);
In the above example, we are adding ‘Zoey’ at the start of the array. In another case, if we need to add an array to the state array follow the below code.
setUsers(current => [...current, ...['Carl', 'Delilah']]);
Adding a value or array we can use the spread operator instead of the push() method, the spread operator creates a new array with the most latest values. In the react js using the useState hook we can use the setState method for updating the state array, with a single value, array, or object.