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
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]);
useEffectruns asynchronously and after a render is painted to the screen.
here are the few things on useEffect
and
useLayoutEffect, on the other hand, runs synchronously after a render but before the screen is updated
useLayoutEffect runs, and React waits for it to finish.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With