Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Vladimir Tsokalo
Use spread syntax to push an element to a state array in React, e.g.
setNames(current => [...current, 'Carl'])
. 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 end of state array setNames(current => [...current, 'Carl']); // 👇️ spread an array into the state array // setNames(current => [...current, ...['Carl', 'Delilah']]); // 👇️ push to beginning of 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.
Notice that 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.
const arr = ['Alice', 'Bob']; const arr2 = [...arr, 'Carl']; console.log(arr2); // 👉️ ['Alice', 'Bob', 'Carl']
The example above creates a shallow copy of the original array.
push()
method directly.Note that this approach can also be used to push an object to 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 object to end of 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 object to beginning of 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 to a state array - we simply unpack the elements of the state array into a new array and add the object.