A, theoretical
-
UseEffect: Frequently used and executed asynchronously, that is, after rendering into the DOM. (Avoid immediate execution of complex DOM operations in the process)
Procedure: First/re-render => React behavior => Real DOM update => useEffect
-
UseLayoutEffect: Scenarios need to be judged. Most of them are used to solve the dom element flash screen problem.
Procedure: First/re-render => React behavior => useLayoutEffect => Real DOM update
-
In most cases, an effect is executed when the corresponding dependency, such as state or props, changes, and the corresponding callback logic often has no immediate or no impact on page vision. (Ajax, Event Emitter)
-
Most of the time, using useEffect is correct. If your code causes flickering, switch to useLayoutEffect.
-
Because useLayoutEffect is synchronous, that is, blocked, the vision won’t update until your effect runs out. If you have computationally intensive code in your Effect, it can cause performance experience problems, such as stuttering. Most effects don’t need to “stop the world” at runtime, and the generic useEffect will do just about everything we need.
Second, the root cause
-
ComponentDidMount, componentDidUpdate and useLayoutEffect(CREATE, DEPS), the browser rendering thread is still blocked, so there is no backflow, redraw process. Since the DOM in memory has been modified, useLayoutEffect can be used to retrieve the latest DOM node and make style changes to the DOM at this point, assuming that the height of the element is changed, These changes will be rendered to the screen at once in Step 11 along with the react changes, again at the cost of a single backflow and redraw.
-
If placed in useEffect, the useEffect function will be executed after the component has been rendered to the screen, and DOM modification will trigger the browser to backflow and redraw again, increasing the performance loss.