useEffect执行时机:
- User interacts with App. Let us say the user clicks a button.
- Component state changes
- The DOM is mutated
- Changes are painted on the screen
cleanup
function is invoked to clean effects from previous render ifuseEffect
dependencies have changed.useEffect
hook is called aftercleanup
.
useLayoutEffect
执行时机:
- User interacts with App. Let us say the user clicks a button.
- Component state changes
- The DOM is mutated
cleanup
function is invoked to clean effects from previous render ifuseLayoutEffect dependencies
have changed.- useLayoutEffect hook is called after cleanup.
- Changes are painted on the screen
useEffect
和useLayoutEffect
最大的区别就是invoke时机,useEffect
hook is invoked after the DOM is painted. useLayoutEffect
hook on the other hand is invoked synchronously before changes are painted on the screen
- use
useLayoutEffect
hook instead ofuseEffect
hook if your effect will mutate the DOM. useEffect hook is called after the screen is painted. Therefore mutating the DOM again immediately after the screen has been painted, will cause a flickering effect if the mutation is visible to the client.useLayoutEffect
hook on the other hand is called before the screen is painted but after the DOM has been mutated. The undesirable behavior, of mutating the DOM immediately after painting the screen, described withuseEffect
hook above can be avoided.