Skip to content

Component not updating when changing a element in a array in useState #32802

Answered by icyJoseph
dladeira asked this question in Help
Discussion options

You must be logged in to vote

Hi,

React compares by reference, in the setState(newState) call, you are just setting state to the same list. Changing the contents of the list doesn't change the reference to the list. When the next state is the same as the old state, React bails out on doing any work.
One quick thing you can do is to slice the array like:

const newData = oldData.slice(0);
newData[0] = 'something'
setState(newData);

Here's an even more in-depth explanation: https://pavi2410.me/blog/dont-use-usestate-to-handle-arrays-in-react, you don't have to do as they say in the article (mutating and forcing render), but it helps you wrap your head around the issue.

Reactivity by assignment just doesn't work like that…

Replies: 2 comments 6 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
6 replies
@Ra-Wo
Comment options

@JS-GitRepo
Comment options

@hschickdevs
Comment options

@naveenbish
Comment options

@anteriovieira
Comment options

Answer selected by dladeira
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
bug Issue was opened via the bug report template.
8 participants
Converted from issue

This discussion was converted from issue #32801 on December 24, 2021 20:29.