Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which React hook executes first useEffect or useLayoutEffect?

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

like image 963
theVoogie Avatar asked Oct 31 '25 00:10

theVoogie


2 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.

like image 174
Manjuboyz Avatar answered Nov 01 '25 15:11

Manjuboyz


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.

like image 32
Robert Avatar answered Nov 01 '25 13:11

Robert