Home  >  Article  >  Web Front-end  >  How do I add elements to an array in React Hooks using useState?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 14:53:02208browse

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

Pushing Elements into Arrays in React Hooks (useState)

When dealing with state arrays in React Hooks, the traditional method is no longer applicable. Instead, useState provides an update method for each state item:

const [arrayState, setArrayState] = useState(initialState);

To add a new element to arrayState, you can call setArrayState with either a new array or a function that creates a new array, typically the latter due to the asynchronous nature of state updates:

setArrayState(prevArray => [...prevArray, newElement]);

In certain discrete events, such as click events, you may be able to omit the callback:

setArrayState([...arrayState, newElement]);

Here's a live example demonstrating the use of the callback:

<code class="javascript">import React, { useState, useCallback } from "react";

function Example() {
  const [arrayState, setArrayState] = useState([]);
  const addEntryClick = () => {
    setArrayState(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
  };
  return [
    <input type="button" onClick={addEntryClick} value="Add" />,
    <div>
      {arrayState.map(entry => (
        <div key={entry}>{entry}</div>
      ))}
    </div>,
  ];
}

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

Remember that the key prop is essential for rendering lists in React for efficient reconciliation and optimal performance.

The above is the detailed content of How do I add elements to an array in React Hooks using useState?. 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