UseLayoutEffect — A Side Note to the Official Doc

The following can be read as a side reference to the official React Doc:

Photo by Toa Heftiba on Unsplash

UseLayoutEffect

I found useLayoutEffect really interesting in comparison to useEffect.

- useEffect runs asynchronously and after a render is painted to the screen.

  1. You cause a render somehow (change state, or the parent re-renders)
  2. React renders your component (calls it)
  3. The screen is visually updated
  4. THEN useEffect runs

- useLayoutEffect, on the other hand, runs synchronously after a render but before the screen is updated. That goes:

  1. You cause a render somehow (change state, or the parent re-renders)
  2. React renders your component (calls it)
  3. useLayoutEffect runs, and React waits for it to finish.
  4. The screen is visually updated
  • Prefer the standard useEffect when possible to avoid blocking visual updates.
  • Because useLayoutEffect is synchronous a.k.a. blocking- the app won’t visually update until your effect finishes running… it could cause performance issues if you have slow code in your effect. Coupled with the fact that most effects don’t need the world to pause while they run.

The only use cases I saw where useLayoutEffect is better than useEffect is to get better/smoothier visual effect (maybe that’s where the “layout’ naming comes from). For example, If your code is causing flickering using useEffect due to the component rendering a partially-ready state first and then immediately re-renders in its final state — that’s a good clue that it’s time to swap in useLayoutEffect.