React useEffect vs. useLayoutEffect
useLayoutEffect
works pretty much same asuseEffect
except thatuseLayoutEffect
executed immediately after the react component render cycle where asuseEffect
waits for a render cycle to get complete and executes.
In the example code above you can see useLayoutEffect triggered before the useEffect
Firing useEffect
- user clicks the button
- state variable gets updated
- React handles the DOM Mutation
- Browsers starts to paint the DOM changes
- useEffect will be triggered
Firing useLayoutEffect
- user clicks the button
- state variable gets updated
- React handles the DOM Mutation
- useLayoutEffect will be triggered
- Browsers starts to paint the DOM changes
If you look at the useEffect and useLayoutEffect
triggering steps you can understand that useLayoutEffect
triggers without waiting for the browser to paint the DOM changes.
When to choose useLayoutEffect over useEffect hook
If your effect
will mutate the DOM, use useLayoutEffect
hook instead of useEffect because 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 will be called before the screen is painted but after the DOM has been mutated. Hence undesirable behaviour of flickering effect will be avoided.