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!