DEV Community

Cover image for Immutability makes tracking changes cheap
Sung M. Kim
Sung M. Kim

Posted on • Originally published at slightedgecoder.com on

3

Immutability makes tracking changes cheap

Photo by Joeri Römer on Unsplash

Note to self
(Meaning, a bit sloppy & is a note to myself but wanted to share still)

Last week’s Weekend Reads topic in r/reactjs was React Docs on 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?

And the state tree would look like below.

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

The post Immutability makes tracking changes cheap appeared first on Sung's Technical Blog.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (2)

Collapse
 
fc250152 profile image
Nando

great point, bro! thank you for sharing :)

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome. Glad you enjoyed it, Nando 😀

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more