I'm trying to figure out the working of React Hook API. I'm trying to add a number to a list. The code that I commented, i.e myArray.push... doesn't seem to perform the operation, though the code below it is working fine. Why is it so?
import React, {useState} from 'react'
export default () => {
const [myArray, setArray] = useState([1,2,3])
return (
<div>
{myArray.map((item=>{
return <li>{item}</li>
}))}
<button onClick = {()=>{
// myArray.push(myArray[myArray.length-1]+1)
// setArray(myArray)
setArray([...myArray, myArray[myArray.length-1]+1])
}}>Add</button>
</div>
)
}
myArray
isthis.state.myArray
and as usual, you shouldn't mutate the state so previously you neverthis.state.myArray.push(....)
, which also means you shouldn't try tomyArray.push
now – Dactylic[...myArray, myArray[myArray.length-1]+1] !== myArray
, which will cause the component to re-render. – Inna===
comparison under the hood, and sincemyArray.push
just adds another element to the existing array, it will not re-render.[...myArray, myArray[myArray.length-1]+1]
however creates an entirely new array. If you stick to the rule of thumb to not mutate the state directly, you will not run into these issues. – Inna