React.js memo – memoization

reactjs

This morning, I came across that React has a memoization function – memo when I was learning about dynamic programming. Like any other memoization implementation, it serves the purpose of recycling calculated result.

“If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. ”  – quoted from reactjs’ documentaiton

This post is to document some of the things that I learned while discussing with my wife, who is much more experienced with react.js.

Our discussion starts with this great tutorial provided by Sam Pakvis, Sam provided some sample code to demonstrate the usage of memo function but it is indeed a bit succinct, or maybe too much that I will add more details in this post.

Environment – codepen.io

When you learn new programming languages, the most difficult part for starters tend not to be the language itself, it is usually the environment which could possibly take you hours even before you start seeing the first output of your “hello world”.

codepen.io is a great online sandbox or online coding editor which you can test out small snippet of code and see the output interactively.

codepen

Component/Props

I am primarily a Python developer so some of the basics of React of even Javascript definitely worth sharing here. A React Component is very much like a Function while the input variables or arguments are called props (short for properties).

Here are a few ways how you can define them:

function Welcome(props) {return result;}
Welcome = (props) => {return results;}
class Welcome extends React.Component { render(){return this.props}}

Lifecycle

When a function is definitely, naturally you need to specify at what time to do what. Like many programming languages like gaming programming in C# for Unity, like processing for Arduino, there is an initialization and following iterations of update or refresh, sometimes infinite. In React, they use the term lifecycle to refer to several built-in methods like DidMount being called when it first got mounted and DidUpdate whenever the state got changed and many others.

componentDidMount, componentDidUpdate

setInterval(() => {}, 1000) will execute a function (1st argument) every 1000ms (2nd argument). In the tutorial, they set a name randomization using setInterval within componentDidMount method.

In the end, there is a built-in method called render which is responsible for rendering the page by returning elements.

render() {return } – JSX

There are some very interesting observations that I made by adding console.log to componentDidUpdate and render. You can simply plugin console.log(‘msg’ + Date()) and it will print out your message and the timestamp. One can quickly realize that both of these two methods got called every 1 sec, the interesting part is that with or without memoization and with/without the state being changed. “Change” is a vague term just as “Same”. In this tutorial, they random select names and you have 1/3 chance of selecting the same name, in that case, the value for sure will stay the same but clearly, React thinks that componentDid(get)Update(d) and it should re”render” the page.

After some research, I realized that the render function might get executed multiple times (literally every 1 second in the tutorial) but it doesn’t mean the web page got “rerendered” every 1 sec. And the “page” got stayed mostly the same and only the specific part got repainted only when a different name got changed.

React.memo

React.memo({prop} => {return xxx}). In this case, whenever there is a prop being passed and the result got calculated. The prop and the corresponding result got cache for later usage. In the tutorial, every second, the prop will be a randomized name. If in the next cycle, the same name got selected, as now the View is a memoization function, it will realize that this name has seen before and instead of return the whole function, it will retrieve the result from cache, return back.

memo_viewmemo_console

As you can tell from the console log, they “skipped” a cycle in 17:18:54 as the BruceSun got picked again at that time, when it got passed to View, it realized that the previous name used was BruceSun, so it decided not to execute View again, hence, there is no data printed for 17:18:54. What is interesting that cache usually can go nuts if the input parameters are very diverse and your cache becomes big. By observing the output, one can clearly see that it is only comparing with the previous state, otherwise, there will only be three lines which each line indicates when its corresponding name got selected. For example, PeterSun got calculated at 17:18:59 and 17:18:55. So the memo in React.js is only cache one record. This is already super helpful for fairly static records.

VirtualDOM (VDOM)

The render method got called every cycle, does that mean our page change every second? The answer could definitely be yes but probably no. Why? In React, this part is really smart. They have some mechanism to determine even if the render got called, certain things happened and the DOM got updated, the updated value could be the same, the updated value could only apply to certain elements, or the update is a complete rebuild of the page, React will efficiently identify the difference between the two versions of DOM and apply the change when necessary.

It is done via something called VirtualDOM.

I watched a Youtube video which talked a bit indepth of each version of DOM between intervals are represented as trees and how the difference got detected and how the real DOM got updated.

Chrome Developer Tool Performance

When I first saw render function got called every second, that strongly made me think that the whole page got rendered or repainted every second too. Even if there is nothing changed on the page, it is still being repainted. Just like a cartoon with multiple frames that are the exact copy, the frames are still the same.

I later on changed my mind after seeing what is actually happening after recording the session in DeveloperTool/Performance/Record. In that, there is an event called repaint who looks like repaint or literally modify the site got called only when there is a name got changed.

console_performance_recordingconsole_performance_eventlogconsole_performance_recording_replay

It looks like a very powerful to front end developers but that convinced me that page only got repainted when there is change.

Conclusion

By studying the tutorial for two hours, you have to acknowledge that the React library is a very powerful tool for building dynamic websites. Due to the nature of a webbrowser, you do have to invest the time to learn the basics of React in order to fully grasp which code serve what purpose because it is just how it is supposed to work, for a reason that you might not be aware of yet but good for sure.

Again, the best way of learning a new library is to invest time covering the basics and also whatever way some of the most experienced React developers recommended.

So RTFM.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s