score:30

Accepted answer

This is because React does a referential equality comparison of props/state when making a decision to rerender.

newArray has the same reference as rollingCards due to which the functional component does not re render on setRollingCards

Change

setRollingCards(newArray)

to

setRollingCards([...newArray])

This creates a new array (new reference) with the elements from newArray

Working solution: https://codesandbox.io/s/admiring-wave-9kgqq

score:1

Because react uses Object.is to determine if the state has changed.

In your code, newArray is the same reference as rollingCards, you can use Object.is(newArray, rollingCards) to check.

const handleClick = () => {
    let newArray = rollingCards;
    newArray.splice(0, 1)   // Object.is(newArray, rollingCards) is true
    setRollingCards(newArray);
}

So you can change it like this.

setRollingCards(rollingCards.filter((item, index) => index !== 0);

Not only this method, as long as it is a different reference


Related Query

More Query from same tag