In React Hooks (useState), you cannot use .push() directly on a state array because it mutates the original array, which won’t trigger a re-render. Instead, you should use immutable updates by spreading the previous state into a new array.
Correct Way to Add Elements to an Array in useState
Use spread syntax (...) to create a new array instead of mutating the existing state.
Example: Adding Items to an Array (Best Practice)
import { useState } from "react";
const App = () => {
const [items, setItems] = useState<number[]>([]); // State as an array
const addItem = () => {
setItems([...items, items.length + 1]); // Spread old items and add a new one
};
return (
<div>
<button onClick={addItem}>Add Item</button>
<ul>
{items.map((item) => (
<li key={item}>Item {item}</li>
))}
</ul>
</div>
);
};
export default App;