Skip to content
Advertisement

React State only updates when setting a useless state variable along with the necessary state variable

State is defined like so:

JavaScript

In this case, id is totally useless. Don’t need it in my app at all.

However, if I try to update items, the state variable doesn’t change and the UI doesn’t reload, unless I also update id:

JavaScript

Why is setId necessary here? What is it doing that setItems isn’t?

Advertisement

Answer

The reason is because setState uses Object.is equality by default to compare the old and the new values and tempItems === items even after you mutate one of the objects inside of it.

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects.

You can solve this by only mutating a copy of the array:

JavaScript

but you’ll run into the same problem if anything depends on item changing, so then you have to copy everything, which is more expensive:

JavaScript

The alternative is to only copy what you’re going to mutate (or switch to an immutable datastructure library like Immer or Immutable.js):

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement