Home > Article > Web Front-end > 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!