useLayoutEffect
is identical touseEffect
, but it fires synchronously after all DOM mutations.one situation you might want to use
useLayoutEffect
instead ofuseEffect
is if you're updating a value (like aref
) and you want to make sure it's up-to-date before any other code runs.both of these hooks can be used to do basically the same thing, but with slightly different use cases.

useEffect
runs after react renders your component
andensures that your effect callback does not block browser painting
.
side effects?
- network request,
- manual DOM manipulation,
- event listeners or timeouts and intervals
it replaces below lifecycle methods:
componentDidMount
useEffect(() => { const intervalId = setInterval(() => { setCount(prevCount => prevCount + 1) }, 1000) return () => clearInterval(intervalId) }, [])```
componentDidUpdate
useEffect(() => { setColor(randomcolor()) }, [count])
componentWillUnmount
refer above example in component did update, the return statement viz. return () => clearInterval(intervalId) shows the use of useEffect as componentWillUnmount
if your effect is mutating the DOM (via a DOM node ref) and the DOM mutation will change the appearance of the DOM node between the time that it is rendered and your effect mutates it, then you
don’t
want to use useEffect.prefer
useEffect
when possible to avoid blocking visual updates.
useLayoutEffect
runs synchronously
immediately after React has performed all DOM mutations
if your effect is mutating the DOM (via a DOM node ref)
and theDOM mutation will change the appearance of the DOM node
between the time that it is rendered and your effect mutates it then you should use useLayoutEffect.otherwise the user could see a flicker when your DOM mutations take effect. (
This is pretty much the only time you want to avoid useEffect and use useLayoutEffect instead.
)this
can be useful if you need to make DOM measurements
(like getting the scroll position or other styles for an element) and then make DOM mutations or trigger a synchronous re-render by updating state.
summary:
useEffect
: if you don’t need to interact with the DOM at all or your DOM changes are unobservableuseLayoutEffect
: if you need to mutate the DOM and/or do need to perform measurements
if you liked this article or found it useful, then a follow would be much appreciated. Alternatively, you could buy me a coffee! All the support is much appreciated. :-)