How to minimize main thread work in React Component
Many a time when we audit our site, we get suggestions to minimize main thread work.
Reducing the main thread work can help you achieve better performance for your web apps.
In this article, we will try to look out for different approaches on how to minimize the main thread work by making some tweaks in the react component.
If you don't know what is the main thread you can easily look here
Let’s get started
We will create a component where we display team size, list of team members, and team name.
In the above snippet here we are accepting three props:
teamMembers,
name and
size.
I have three different APIs to get team size, name, and list of available members.
Depending upon our backend API the props will update and the component rendering takes place.
Anytime props name and size get a new value, the function showAvailableMembers() will be called, whose job is to display a list of team members causing our main thread to block for a while.
We know React is smart enough to check the diff which won't re-render my list, but our JS main thread will still be blocked till it maps over the list, although re-render won't happen.
Solution
We will make use of the react state and make some changes in the code accordingly.
To control when to call the function, we will make use of the state.
We will add a check as show below
Inside our function showAvailableMembers
we update the value forlistJsx
flag.
So now if name
or size
prop update our listJsx
will always be true
and our function showAvailableMembers
will never be called which eventually won't block our main thread.
Make use of componentDidMount
Another solution is we can make use of componentDidMount
and check if (!listJsx && teamMembers.length)
then call showAvailableMembers
but there’s a catch if your app required SSR componentDidMount
will not run on the server.
Conclusion
With such approaches, we can definitely increase our performance by reducing the main thread work which will help to increase time to interactive of the app.
I hope you enjoyed reading this article.
Thank you.
P.S. 👋 Hi, I’m Aatif! If you liked this, follow me on twitter and share the story with your developer friends