With React hooks, it might not be immediately obvious how we can push items into an array state.
In this article, we’ll look at how to push an item into an array if we have an array state with React hooks.
Use the State Setter Function
The state setter function returned by useState
lets us pass in a callback that takes the previous value of a state and returns a new one.
Therefore, we can just return a copy of the array and then append the entry we want to push to the end of it.
For instance, we can write:
import { useState } from "react";
export default function App() {
const [arr, setArr] = useState([0]);
return (
<div className="App">
<button
onClick={() => setArr((arr) => [...arr, arr[arr.length - 1] + 1])}
>
push
</button>
<p>{JSON.stringify(arr)}</p>
</div>
);
}
We create the arr
state with the useState
hook.
The setArr
function lets us set the new value of the arr
state.
We pass in the initial value into the useState
hook.
In the button, we have the onClick
prop set to a function that calls setArr
with a callback.
The arr
parameter has the existing value of the arr
state.
And we return a copy of the arr
state with a value at the end.
Then below that, we show the stringified version of the arr
value.
Therefore, when we click on the push button, we see new numbers being added to the arr
array.
This is the most reliable way to push an element into a state array.
We can also just update the array state directly without a callback in some situations.
If we’re adding a click handler we do before, we can also just update the array directly with a new array.
For instance, we can write:
import { useState } from "react";
export default function App() {
const [arr, setArr] = useState([0]);
return (
<div className="App">
<button onClick={() => setArr([...arr, arr[arr.length - 1] + 1])}>
push
</button>
<p>{JSON.stringify(arr)}</p>
</div>
);
}
We pass a copy of the arr
array with the new value at the end directly into the setArr
function.
This works for some situations like click handlers.
However, it may not work with mouse move event handlers.
Also, we can write:
import { useState } from "react";
export default function App() {
const [arr, setArr] = useState([0]);
return (
<div className="App">
<button onClick={() => setArr(arr.concat(arr[arr.length - 1] + 1))}>
push
</button>
<p>{JSON.stringify(arr)}</p>
</div>
);
}
The concat
function also returns a new copy of the arr
array with the item we want to append at the end.
Conclusion
There are various ways we can push an array item into an array state with state setter functions.