import React from 'react';
import ReactDOM from 'react-dom';
function App() {
const [thingsArray, setThingsArray] = React.useState(["Thing 1", "Thing 2"])
function addItem() {
setThingsArray(prevThingsArray => prevThingsArray.push("Thing 3"))
}
const thingsElements = thingsArray.map(thing => <p key={thing}>{thing}</p>)
return (
<div>
<button onClick={addItem}>Add Item</button>
{thingsElements}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
According to my understanding when we want to change state we should use a call back function inside the function which we use to update state . And in that callback function we use a parameter to reference to current value of state as we should not directly change state . In below example i am using the same idea but it is not working , can anyone explain me the reason and logic behind it?