Why React and Redux need immutable data
Explaining with drawings and examples, so we can finally understand it.
React uses shallowCompare when deciding if it should re-render a component.
johnClone has the same name and age of
john, but they are not the same person.
When we declared
john = people, we didn’t copy
people name and age to
john. Both variables point to the same object as reference.
Now, let’s see a shallowCompare example:
If we want to console john’s updates, we need to clone it. This way, shallowCompare will know that props have changed.
React uses the same principle to avoid unnecessary component re-renders.
If we click on the button, the component will not render john’s updates because the
people is the same reference from the last time. For that reason, we can not mutate
john. We need to clone
john before and then update the array.
Realize that we didn’t clone
people (mary). Immutable data doesn’t mean that we have to exhaustively clone all object’s ramifications. It would not be very efficient. We just need to create new references through the path we changed.