0

I just wonder what's the best practice here. I noticed that React strict mode calls a state setter twice, so if I have e.g.

setArray(function(arr){
  arr.push(arr.length);
  return [...arr];
})

it will push twice to the same array and then return the 'wrong' result. In this case I could fix it by doing

setArray(function(arr){
  const newArr = [...arr];
  newArr.push(arr.length);
  return newArr;
})

but what if my state is more complex, e.g. nested objects and I only want to update the innermost one? In this case I'd need to create a copy of the inner object, then alter it, then create a shallow copy of the outer object and place the new inner object inside, then return. This sounds complicated, is this really how it's meant to be?

(Notice that all of this works just fine without strict mode, but my understanding is that strict mode teaches you best practices when using React.)

3
  • Maybe using some library like Immer as docs suggest too ... see here .. Commented Oct 18, 2022 at 7:41
  • 1
    Ah cool, I heard about Immer but I didn't know that it's even in the official docs. Thanks a lot! Feel free to answer the question with this comment if you want, or I might delete it later. Commented Oct 18, 2022 at 7:41
  • 1
    you can delete no worries or may be keep it as it and helps some one else looking for same :) Commented Oct 18, 2022 at 7:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.