DEV Community

Cover image for I used useLayoutEffect
Daniel Bellmas
Daniel Bellmas

Posted on

I used useLayoutEffect

Yes yes…I used this misunderstood hook.
Let’s simplify.

The difference between useLayoutEffect and useEffect is when each hook is executed.

React’s lifecycle:

  1. State changes in reaction to the user interacting with the UI.
  2. useLayoutEffect is executed.
  3. The browser paints the change, meaning, the user sees the changed UI.
  4. useEffect is executed.

As we can see the useLayoutEffect happens before the useEffect, and more importantly, happens before the browser represents that change in the UI.
This is why the solution to my flickering UI problem was switching from useEffect to useLayoutEffect.

When should you prefer useLayoutEffect?

If you need to update the DOM and make visual changes to the UI on the initial mount, you should use useLayoutEffect.


Here is a close approximation of a real-life example where I used useLayoutEffect to solve the flickering problem I had.

Breakdown:

  • Pressing the on the click button will reset the state to its initial state.

In the real example I didn't press a button to initialize the state, the component unmounted and then mounted again which caused the state to re-intialize and the UI to flicker.

  • If the state equals the initial state, then we don't show the text: The number is: [number].
{displayedNumber && <div> The number is: {displayedNumber}</div>}
Enter fullscreen mode Exit fullscreen mode

This is the line that causes the flicker. because at the same time we're updating the displayedNumber state to be equal to the number (in the useEffect).
Therefore, we have a quick removal of the text and its return, which causes the UI to flicker.

When using useEffect we have a UI flicker because it happens after the browser paints.
useEffect GIF


When using useLayoutEffect we don't have a UI flicker because it happens before the browser paints.
useLayoutEffect GIF

Top comments (0)