I am writing a code in react/react hooks that attempt to do the following.
Get an array of objects from the parent component as a prop
Set it as a state using useS
React checks for changes in props and state by doing a shallow object equality check. If you set the state to the same object you received from state, React assumes you aborted your change and doesn't do anything, even if the properties on the object changed.
The key is that the sort()
method sorts the array in place, and returns a reference to the same array. So React sees it as the same array object, even though the orser of its entries is different.
The solution is to create a new array:
let k = [...newarray];
When k
is passed to setnewarray
, React sees that it is an entirely different object, and triggers the rerender.