when to useLayoutEffect over useEffect?

Chinmay
3 min readAug 22, 2022

useLayoutEffect is identical to useEffect, but it fires synchronously after all DOM mutations.

one situation you might want to use useLayoutEffect instead of useEffect is if you're updating a value (like a ref) 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 vs. useLayoutEffect mind map (https://mm.tt/map/2391836247?t=5gPdn7abze)

useEffect

  • runs after react renders your component and ensures that your effect callback does not block browser painting.

side effects?

  1. network request,
  2. manual DOM manipulation,
  3. 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 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 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 unobservable
  • useLayoutEffect: 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. :-)

https://www.linkedin.com/in/chinmay-kude

--

--

Chinmay

I often describe myself as a software professional having the mindset to break things but the toolset to create and restore.