Member-only story
How to Add to an Array in React State using Hooks
The .push()
function will not work, but the .concat()
function can update state in React when state is a JavaScript array — as can …
, the spread operator.
“One of the most common questions is how to add an item to an array in React state. Since you are not allowed to mutate the state directly, you cannot simply push an item to an array.” — Robin Wieruch in a 2018 blog post
When React state is an array, it is not obvious how to add items to the array, such as when trying to update state using React Hooks.
This question might come up when state is a list of items. In this article, I explore an example of the recent search queries entered by the user.
A more complex example would be storing a list of JavaScript objects as an array in the React state, such as student records.
The question is how do I add an item to the array in React State?