React - Get rid of the flicker on first render using useLayoutEffect

Ever noticed an annoying flicker happening when you do some DOM calculations/changes inside useEffect?

That's because useEffect is called "after the render is committed to the screen"

What does that even mean??

To properly understand this, we need to keep something in mind: Rendering != Painting New DOM Changes

Many developers when they hear "rendering" they think of it as "updating the DOM", but that's not very accurate.

Rendering means calling the functional component that had some state changes, and calculating what new changes need to be done to update the current DOM.

But this alone doesn't update what the user sees on the screen! There is still a final step which is the "Committing". Which means applying the changes that were calculated by the rendering step on the actual DOM.

Okay okay, that's cool and all...

But what does this have to do with the flickering that you mentioned??

We said earlier that useEffect is called AFTER the changes are painted to the screen, right? So if we want to make some changes to the DOM & we don't want this flickering to happen, we need to do that AFTER the rendering but BEFORE the painting. And that's where useLayoutEffect comes to rescue, cause it does just that.

A real-world example for this is when we want to implement the FLIP animation technique that I talked about in a previous post.

If you remember, we calculate the delta transform between the initial & final states, then we inverse it to look like it didn't move from its initial position at all, but if we did that in useEffect, then it would appear in its final position for just a moment before the inverse is applied, so all we need to do is to do this in useLayoutEffect. And problem solved!!!

So should we always use useLayoutEffect instead of useEffect??

Absolutely NOT. For 97% of the cases, useEffect is the better option. Only in the rare cases where you wanna mutate the DOM or perform measurements you should use useLayoutEffect.

And that's it folks. Leave a like if you learned something interesting.

And have a nice day 👋

My Photo

About Me

I'm a freelance web developer who specializes in frontend.
I have a special love for React. And my personal goal is: Building things that are Awesome! ✨
If you are someone who is building a project where high quality is a MUST, then Let's Chat! I'll be glad to help you with it.

© 2023-present Mohammed Taher Ghazal. All Rights Reserved.