) }
If you're running the above code, you'll see that both functions add 0 at the start and end of the array. However, it does not add 0 to the array printed on the page. You can repeatedly click this button, but the UI remains the same.
Cause in both functions you are changing state with array.push() . React explicitly warns that state must be immutable in React, meaning you cannot change it. React uses reference values with this state.
The solution here is to access the current state (currentArray), make a copy of the state and an update for that copy:
function addNumberToStart(number) { setArray((currentArray) => { return [number, .currentArray] }) } function addNumberToStart(number) { setArray((currentArray) => { return [.currentArray, number] }) }
This is the correct method to update state in React. Now when you click the button, it adds zeros to the beginning and end of the array. But the most important here is that the updates will reflect immediately on the page.
Above are the React programming mistakes to avoid . Hope the article is useful to you.