How to Push or Append an Element to a State Array with React Hooks?

On many occasions, we may have states that are arrays.

We may want to push items to the end of the array.

The way to do it may not be immediately obvious to us.

In this article, we’ll look at how we can push or append an element to a state array with React hooks.

Pass in a Callback that Returns a New Array to the State Setter Function

To update the state array with a new element at the end of it, we can pass in a callback that returns a new array with the new item added to the end of it.

To do this, we write:

import React, { useState } from "react";

export default function App() {
  const [arr, setArr] = useState(["foo"]);
  return (
    <div className="App">
      <button onClick={() => setArr((oldArray) => [...oldArray, "foo"])}>
        add
      </button>
      <div>
        {arr.map((a, i) => (
          <p key={i}>{a}</p>
        ))}
      </div>
    </div>
  );
}

We have the setArr state setter function defined with the useState hook.

The initial value of the arr state is an array as we have in the argument of useState .

We have the onClick handler that calls the setArr function with a callback that takes the oldArray parameter, which is the old value of the arr state.

And we return an array with the existing items spread from oldArray and the new item at the end of the array.

In some situations like adding items on click, we can also pass in the new array value directly to the state setter function.

So we can also write:

import React, { useState } from "react";

export default function App() {
  const [arr, setArr] = useState(["foo"]);

  return (
    <div className="App">
      <button onClick={() => setArr([...arr, "foo"])}>add</button>
      <div>
        {arr.map((a, i) => (
          <p key={i}>{a}</p>
        ))}
      </div>
    </div>
  );
}

When we want to add a new array entry on click.

We can also use the concat method to return an array with the new value at the end of it.

For example, we can write:

import React, { useState } from "react";

export default function App() {
  const [arr, setArr] = useState(["foo"]);

  return (
    <div className="App">
      <button onClick={() => setArr((oldArray) => oldArray.concat("foo"))}>
        add
      </button>
      <div>
        {arr.map((a, i) => (
          <p key={i}>{a}</p>
        ))}
      </div>
    </div>
  );
}

We call concat on the oldArray with the argument of it being the new item we want to add.

And so we get the same result as before.

Conclusion

To update a React component state array with a new item at the end of it, we can pass in a callback to the state setter function that takes the old array value and return the new array value.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics