3 ms·
> setState doesn't actually care whether you've mutated your data or updated it immutably. Not necessarily - if something downstream is looking at the values (
by amk_ 9y ago
> setState doesn't actually care whether you've mutated your data or updated it immutably.
Not necessarily - if something downstream is looking at the values (such as a shouldComponentUpdate check), the first mutation may cause the current value to === the next value and prevent a render. I know you called this out as an "optimization" but you don't always know what's happening inside your components, especially if 3rd party libraries are involved.
- acemarke 9y agoThat's what I was saying. The actual `setState()` function can be called with new references from immutable data, the same references that already existed but were mutated, or even no references at all if you mutated. So, literally, `setState()` does not care what process you used to potentially update data before calling it - it just applies a shallow merge of whatever object you passed in to the existing `this.state` object, and then queues a re-render. It's the _rest_ of your code that might care. The primary reasons to actually update data immutably before calling `setState` are for easy and consistent implementation of `shouldComponentUpdate` / use of `PureComponent`, and general FP principles that immutability should be preferred over mutation.