by Anthony Ng
What I learned from reading defer-render-hoc and why it’s useful.
This is another article for my Deliberate Practice. Why am I doing this? Read this article to learn more.
I was reading through this article about how Twitter Lite (a React PWA) removed performance bottlenecks.
When the user taps the Home
button, there is a delay until the tweets are shown. This delay was caused by a large number of components mounting and unmounting. defer-render-hoc
is an Open Source project that implements the solution given in the article.
Let’s look at the code
defer-render-hoc
is a Higher Order Component (HOC). To learn more about it, read the documentation here.
We use defer-render-hoc
by wrapping your Expensive Component with it.
defer-render-hoc
renders null
on the initial render.
So when will defer-render-hoc
render your Expensive Component? It uses requestAnimationFrame
to wait two frames. After two frames have passed, it will render your Expensive Component.
requestAnimationFrame
is usually used to create smooth animations (read more about it in this article).
Here, we are using requestAnimationFrame
to allow other components to update and give control back to the user. After the two frames, our Expensive Component takes over.
Demo
Check out this CodeSandbox for a demo of defer-render-hoc
.
Click from the Cheap page
button to the Expensive page
button. Notice how the button stays blue as the UI freezes.
Our click event takes 620ms. The click event does not finish until our Expensive Component mounts. Because of that, the screen is frozen for the user.
Now, click from the Cheap page
button to the Deferred Expensive page
button. Notice how the button does not stay blue, and the UI is not frozen.
Our click event takes 16ms. The click event doesn’t wait for our Expensive Component to mount; the work is deferred. The screen doesn’t freeze.
How does this help?
The same amount of work still happens. The Expensive Component still mounts; it just mounts later. The experience itself is not faster overall. It might even be slower with the overhead of the defer-render-hoc
. But sometimes a faster perceived experience is more important than an actual faster experience. See the below links for more information about perceived performance.
- https://en.wikipedia.org/wiki/Perceived_performance
- https://medium.com/@lukejones/a-designers-guide-to-the-perception-of-performance-fedb4bd102b
Depending on your project, defer-render-hoc
might be right for you.