How to Add Element to useState Array in JavaScript

How can we append an element to an array stored in our component state in JavaScript?

Suppose we’re working in React.js or Next.js and we have an array stored in our component state.

const [users, setUsers] = useState([]);

Push element to end of array

The recommended way to append an element to an array is to use a wrapper function that will create and return the new array. We’ll use this wrapper function in our set function.

We can dump all the contents of the current state array into a new list using the spread operator, and then add the new element at the end.

const addUserToEnd = (newUser) => {
  setUsers(state => [...state, newUser])

Push element to beginning of array

Similarly, we can insert the element to the beginning of the array.

const addUserToBeginning = (newUser) => {
  setUsers(state => [newUser, ...state])

Feel free to read about how to delete elements in a useState array and update objects in a useState array.