Last updated: Apr 7, 2024
Reading timeยท4 min
Use the spread syntax to push an element into a state array in React, e.g.
setNames(current => [...current, 'New'])
.
The spread syntax (...) will unpack the existing elements of the state array into a new array where we can add other elements.
import {useState} from 'react'; export default function App() { const [names, setNames] = useState(['Alice', 'Bob']); const handleClick = () => { // ๐๏ธ Push to the end of the state array setNames(current => [...current, 'Carl']); // ๐๏ธ Spread an array into the state array // setNames(current => [...current, ...['Carl', 'Delilah']]); // ๐๏ธ Push to the beginning of the state array // setNames(current => ['Zoey', ...current]); }; 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> ); }
We used the useState hook to manage a state array.
const [names, setNames] = useState(['Alice', 'Bob']);
We passed a function to setState
because the function is guaranteed to be
invoked with the current (most up-to-date) state.
setNames(current => [...current, 'Carl']);
When the next state is computed using the previous state, pass a function to
setState
.
We used the spread syntax (...) to unpack the elements of the existing array into a new array and added another value at the end.
const arr = ['Alice', 'Bob']; const arr2 = [...arr, 'Carl']; console.log(arr2); // ๐๏ธ ['Alice', 'Bob', 'Carl']
The example creates a shallow copy of the original array.
push()
method directly.If you get the warning prop spreading is forbidden, click on the link and follow the instructions.
If you need to remove an element from a state array, check out the following article.
If you need to push the elements of an existing array into a state array, use the spread syntax (...) to unpack the values.
import {useState} from 'react'; export default function App() { const [names, setNames] = useState(['Alice', 'Bob']); const handleClick = () => { const arr = ['Carl', 'Delilah']; setNames(current => [...current, ...arr]); }; 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> ); }
We used the spread syntax (...) twice in the same statement to push the elements of an existing array into the state array.
const handleClick = () => { const arr = ['Carl', 'Delilah']; setNames(current => [...current, ...arr]); };
If you need to add a value to the beginning of a state array, place it before the spread syntax in the expression.
const handleClick = () => { setNames(current => ['Zoye', ...current]); };
This approach can also be used to push an object into a state array.
import {useState} from 'react'; export default function App() { const initialState = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const [employees, setEmployees] = useState(initialState); const handleClick = () => { // ๐๏ธ push an object to the end of the state array setEmployees(current => [...current, {id: 3, name: 'Carl'}]); // ๐๏ธ spread an array of objects into the state array // setEmployees(current => [ // ...current, // ...[ // {id: 3, name: 'Carl'}, // {id: 4, name: 'Delilah'}, // ], // ]); // ๐๏ธ push the object to the beginning of the state array // setEmployees(current => [{id: 3, name: 'Zoey'}, ...current]); }; return ( <div> <div> <button onClick={handleClick}>Push to state array</button> </div> {employees.map((element, index) => { return ( <div key={index}> <h2>{element.name}</h2> </div> ); })} </div> ); }
The same approach can be used to push an object into a state array. We simply unpack the elements of the state array into a new array and add the object.
If you need to push an array of objects into the state array, use the spread syntax to unpack the second array.
import {useState} from 'react'; export default function App() { const initialState = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const [employees, setEmployees] = useState(initialState); const handleClick = () => { // ๐๏ธ spread an array of objects into the state array const arr = [ {id: 3, name: 'Carl'}, {id: 4, name: 'Delilah'}, ]; setEmployees(current => [...current, ...arr]); }; return ( <div> <div> <button onClick={handleClick}> Push to state array </button> </div> {employees.map((element, index) => { return ( <div key={index}> <h2>{element.name}</h2> </div> ); })} </div> ); }
We used the spread syntax twice in the same statement to add an array of objects to the state array.
const arr1 = [ {id: 1, name: 'Alice'}, {id: 1, name: 'Bob'}, ]; const arr2 = [ {id: 3, name: 'Carl'}, {id: 4, name: 'Delilah'}, ]; const newArray = [...arr1, ...arr2]; // [ // { id: 1, name: 'Alice' }, // { id: 1, name: 'Bob' }, // { id: 3, name: 'Carl' }, // { id: 4, name: 'Delilah' } // ] console.log(newArray);
The order in which we unpacked the arrays is preserved.
If you need to add an object to the beginning of a state array, place the object before using the spread syntax.
const obj = {id: 1, name: 'Alice'}; const arr = [ {id: 2, name: 'Bob'}, {id: 3, name: 'Carl'}, ]; const newArray = [obj, ...arr]; // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' }, // { id: 3, name: 'Carl' } // ] console.log(newArray);
If you need to update an array of objects state in React, check out the following article.
You can learn more about the related topics by checking out the following tutorials: