How to insert into React’s state array with useState?

Sometimes, we want to insert into React’s state array with useState.

In this article, we’ll look at how to insert into React’s state array with useState.

How to insert into React’s state array with useState?

To insert into React’s state array with useState, we call the state setter function with a callback that returns the new state array with the value we want inserted.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [myArray, setMyArray] = useState([]);

  const insert = () => {
    setMyArray((myArray) => [...myArray, Math.random()]);
  };

  return (
    <div>
      <button onClick={insert}>insert</button>
      {myArray.map((a) => (
        <p key={a}>{a}</p>
      ))}
    </div>
  );
}

to define the myArray state array with useState set to an empty array as its initial value.

Then we define the insert function that calls setMyArray with a callback that returns the new array with a random number attached at the end of it.

Next, we add a button that has the onClick prop set to insert.

And finally we render the myArray values with myArray.map.

As a result, when we click insert, we should see new numbers displayed.

Conclusion

To insert into React’s state array with useState, we call the state setter function with a callback that returns the new state array with the value we want inserted.