Home > Software design >  Set state in useEffect and have it in its dependencies array
Set state in useEffect and have it in its dependencies array

Time:01-12

Please look at this

useEffect(() => {
  setName('John');
}, [name]);

How come it does not cause an infinite loop? assuming name is not already equal to John.

CodePudding user response:

because this does not update the useState hook ! or let's say update it with the same value so useEffect don't run

CodePudding user response:

Because useState is using a diffing algorithm (or they are calling it Bailing out - in the official documentation) to make a comparison for objects/values. So in this scenario, React will compare the previous value of name and will see that it's the same and won't invoke the setter.

The same will happen if you try to update the same object, obj = { name: 'John' } (obj) React will make a comparison and see that it's the same object and won't make any change, but if you spread that object and invoke the setName({ ...obj }) in this scenario React will treat it like different object and invoke the setName.

  • Related