useEffect vs. useLayoutEffect

useEffect vs. useLayoutEffect

·

1 min read

Question : I'm wondering, if we could use useLayoutEffect instead of useEffect here as well.

Answer:

useLayoutEffect runs before the useEffect hook. This is because the useLayoutEffect is fired synchronously after DOM gets mutated and before the browser paints the new changes.

This means that the useEffect hook will get triggered right after the browser paints which is what we want in this case. So using the useEffect hook is what is recommended here. You should use the useLayoutEffect when you are directly updating the DOM to avoid flickering. Also another thing to note here is that useEffect runs in an asynchronous fashion whereas the useLayoutEffect runs in a synchronous fashion. So the difference is in the time at which these functions get invoked.