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.
And the state tree would look like below.
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
- Optimizing Performance – Official React Documentation
- [Weekend Reads] React Docs on Optimizing Performance
-
Immutable User Interface – Lee Byron in Render 2018
- Haven’t finished watching it, yet
- Just found it from Dan’s tweet.
The post Immutability makes tracking changes cheap appeared first on Sung's Technical Blog.
Top comments (2)
great point, bro! thank you for sharing :)
You're welcome. Glad you enjoyed it, Nando 😀