Explaining with drawings and examples, so we can finally understand it.

André Gardi
Sep 30 · 2 min read

Short answer:

React uses shallowCompare when deciding if it should re-render a component.

References

To understand shallowCompare, we need, first, to know how JavaScript handles objects references. Let's see an example:

johnClone has the same name and age of john, but they are not the same person.
When we declared john = people[1], we didn’t copy people[1] name and age to john. Both variables point to the same object as reference.

ShallowCompare

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 example

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[1] 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[0] (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.

JavaScript in Plain English

Learn the web's most important programming language.

André Gardi

Written by

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade