React, useEffect and useLayoutEffect Gotchas
The difference between the useEffect
and useLayoutEffect
can be vauge. In
daily task 99% of the time useEffect
is way to go. Yet it's nice to now the
difference since it can be useful in some situtations also it's a great
interview question!
useEffect
99% of the time this is what we want to use. useEffect
allows you to synchronize a component with an external system.. When useEffect
is called, React knows to render your side effect
only after changes are made to the DOM
useEffect
runs after every react render (including the first render). useEffect
is
effected only after the component is rendered so it ensures that your effect
callback does not block browser painting.
If you need your effect to fire synchronously after the DOM mutation before the next browser paint. You wil need to use
useLayoutEffect
. Otherwise users could see flickering or visual inconsistencies when DOM mutations take effect.
useLayoutEffect
useLayoutEffect
is a version of useEffect
that fires before the browser repaints the screen.
useLayoutEffect
runs synchronously immediately after the DOM mutation and before the
browser get to paint the new changes.
This hook is useful for performing DOM measurement (like getting scroll height, scroll position).
Summary
useEffect | useLayoutEffect |
---|---|
Do not need to interact with DOM | Need to mutate DOM / need to perform measurements |
Runs after every render, including first render. | Runs immediately after DOM has been updated/before browser had a chance to "paint" the changes |
Also read: