Which React hook executes first useEffect or useLayoutEffect?

Viewed 910

I have a component and I want to do some calculations right before rendering HTML on the screen. Since both useEffect and useLayoutEffect can handle this task, my question is having both of them in code, which of them will be triggered first, useEffect and useLayoutEffect?

Cheers

3 Answers

It is again your own way of coding however, here is small info and you can always look into something more.

useEffect(() => {
  // do side effects
   return () => /* cleanup */
 }, [dependency, array]);

 useLayoutEffect(() => {
  // do side effects
 return () => /* cleanup */
 }, [dependency, array]);

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

here are the few things on useEffect

  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.

and

useLayoutEffect, on the other hand, runs synchronously after a render but before the screen is updated

  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

So as @Robert suggested use useEffect most of the time.

UseLayoutEffect is synchronous and it'll block your app. It'll also cause additional render.

I suggest using useEffect and leave useLayoutEffect for some edge cases.

useEffect() runs after the browser paint, useLayoutEffect() runs before the paint. So, useLayoutEffect() runs first, before useEffect(). You can test it yourself by placing console.log() in both of the functions and see which one executes first.

Related