Course
useLayoutEffect
React Mastery Guide
Unlock the full potential of React with our comprehensive guide. From basics to advanced techniques, this course covers everything you need to build dynamic, high-performance web applications. Perfect for developers at any level, start mastering React today!
useLayoutEffect
Similar to useEffect, there is another hook called
useLayoutEffect
.In most cases, replacing useEffect with useLayoutEffect works the same:
useEffect(() => { console.log('This is a log..'); queryData().then((data) => { setNum(data); }); }, [1, 2, 3, ‘xxx’]);
Try it out!
So why do we have both hooks?
We know that JavaScript execution and rendering are blocking processes:
The useEffect hook will be executed asynchronously after manipulating the DOM.
Asynchronous execution is handled using APIs like
setTimeout
, Promise.then
, etc., which wrap the logic to be executed.
Thus, the asynchronous execution of effect logic has two possibilities:
The effect may complete execution before the next render:
Or it may not have time to execute before the next render, so it runs after the render:
This can sometimes cause flickering, as the state during the first render is the previous value. After rendering, the effect runs and updates the state, causing a re-render with the new value.
Generally, this isn't a big issue, but if you encounter this flickering and want to avoid it, use
useLayoutEffect
.The difference is that the effect in
useLayoutEffect
runs synchronously, within the same task:
This means the browser will wait for the effect logic to complete before rendering.
The advantage is no flickering.
But the downside is obvious: It will block rendering.
What if the effect logic takes a long time to execute?
Tasks longer than 50ms are considered long tasks, which block rendering and cause frame drops:
Therefore, in general, it is better to execute effect logic execute asynchronously.
That is to say, in most cases, use
useEffect
as it can avoid page stuttering (frame drops) due to long-running effect logic. But if flickering is a significant issue, you can use useLayoutEffect
, ensuring the effect logic doesn't take too long to execute.Both synchronous and asynchronous execution of effects have their pros and cons. This is why React provides both
useEffect
and useLayoutEffect
, allowing developers to decide which one to use.