Home >Web Front-end >JS Tutorial >How do I add elements to an array using the useState hook in React?

How do I add elements to an array using the useState hook in React?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 07:37:02253browse

How do I add elements to an array using the useState hook in React?

Push elements into arrays with useState in React

When using the useState hook in React, you can modify your state array by invoking its update method. This method is provided when you initialize the state item, such as:

<code class="js">const [theArray, setTheArray] = useState(initialArray);</code>

To add a new element to the array, pass in the updated array or a function that generates the new array to the setTheArray method. The latter is typically used because state updates in React are asynchronous and may occur in batches.

<code class="js">setTheArray(oldArray => [...oldArray, newElement]);</code>

Alternatively, this shortcut syntax may suffice if you're only making updates within handlers for specific user events (like clicks, but not mouse movement):

<code class="js">setTheArray([...theArray, newElement]);</code>

Events that trigger rendering flushes in React are known as "discrete events."

Live example:

<code class="js">const { useState, useCallback } = React;
function Example() {
  const [theArray, setTheArray] = useState([]);
  const addEntryClick = () => {
    setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
  };
  return [
    <input type="button" onClick={addEntryClick} value="Add" />,
    <div>
      {theArray.map(entry => <div>{entry}</div>)}
    </div>
  ];
}

ReactDOM.render(
  <Example />,
  document.getElementById("root")
);</code>

The above is the detailed content of How do I add elements to an array using the useState hook in React?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn