How to push an Element into a state Array in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
4 min

banner

# Push an element into a state Array in React

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.

App.js
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> ); }

push to state array

The code for this article is available on GitHub

We used the useState hook to manage a state array.

App.js
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.

App.js
setNames(current => [...current, 'Carl']);

When the next state is computed using the previous state, pass a function to setState.

Otherwise, we might get a race condition if the state array we have access to doesn't store the most up-to-date value.

We used the spread syntax (...) to unpack the elements of the existing array into a new array and added another value at the end.

App.js
const arr = ['Alice', 'Bob']; const arr2 = [...arr, 'Carl']; console.log(arr2); // ๐Ÿ‘‰๏ธ ['Alice', 'Bob', 'Carl']

The example creates a shallow copy of the original array.

When working in React, it isn't allowed to mutate the original state array, so we can't use the 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.

# Pushing the elements of an existing array into a state array

If you need to push the elements of an existing array into a state array, use the spread syntax (...) to unpack the values.

App.js
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> ); }

push elements of existing array into state array

The code for this article is available on GitHub

We used the spread syntax (...) twice in the same statement to push the elements of an existing array into the state array.

App.js
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.

App.js
const handleClick = () => { setNames(current => ['Zoye', ...current]); };

# Pushing an object into a state Array in React

This approach can also be used to push an object into a state array.

App.js
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> ); }

push to state array

The code for this article is available on GitHub

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.

App.js
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> ); }

push elements of existing array into state array

The code for this article is available on GitHub

We used the spread syntax twice in the same statement to add an array of objects to the state array.

App.js
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.

App.js
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);
The code for this article is available on GitHub

If you need to update an array of objects state in React, check out the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev