← Go Back

Immutability makes tracking changes cheap

Broken Post?Let me know

Photo by Joeri Römer on Unsplash

Note to self...

This week's Weekend Reads in r/reactjs was for Optimizing Performance.

An ah-ha moment when reading the article regarding immutability.

Suppose that you have a component, Post that has to render a comment thread like this.

Reddit Post: What's a joke that's so stupid it's funny?

reddit comments

Reddit Comments

And the state tree would look like below.

comment tree

Post state tree

When JavaScript compares two values, primitive type (number, string, boolean, etc) comparisons shown in the state tree, such as id, date, author, are cheap.

When you have to compare object type states, a comparison is done by reference.

So if someone has modified one of the items in comments array, you have to traverse every item in the comment to find out if anything has changed.

It's an O(n) operation process thus it's slow 🦄.

But if you had returned a new comments array (using Object.assign or object spread, {...}) then reference has changed, thus you know that something has changed.

Now it's an O(1) operation, blazing fast 🏎.

TIL

If your state is immutable, then React can reconcile which state to update cheaply.

You can still override shouldComponentUpdate if you need need more control.

Resources