Hello

I'm Alejandro

A Web Engineer from Málaga, Spain based in London, UK

useEffect and useLayoutEffect

From React's 16.8 release, there has been quite a change in the way we use to write React components. In this version, the React team introduced Hooks, allowing you to share your component logic and not write a single class anymore. People reacted very well to this change and started rewriting all their code to Hooks, removing complexity and making their codebase smaller.

useEffect is one of the most popular hooks and came to replace componentDidMount, componentDidUpdate, and componentWillUnmount.

You probably know how it works. But did you know useEffect has a big brother? It's called useLayoutEffect.

Let's compare both and see when it will be the case in which you will need to use it.

useEffect

To be used, when the component mounts.

useEffect(() => {
  // your effect code
}, [])

Or when your component updates.

useEffect(() => {
  // your effect code
}, [state]) // whenever "state" changes, re-run effect code

Or when your component unmounts.

useEffect(() => {
  // your effect code

  return () => {
    // your effect unmount code
  }
}, [])

You will want to use useEffect 99% of the times. But there is one caveat, and this is when your effect code is mutating the DOM and this mutation changes your DOM between the time React rerenders and your effect code mutates it.

If you use useEffect for this kind of operations, your user will most likely see an inconsistent flickering UI, and we don't want that.

useLayoutEffect

Implementation is exactly the same as useEffect, but useLayoutEffect, will wait until React finishes with all its DOM manipulations and then do yours. This is the main difference.

You will want to use useLayoutEffect if, for example you want to get an element width and height or position in your page, or when you want to see where your element is related with the scroll of the page...etc.

Conclusion

  • Use useLayoutEffect when you need to do DOM manipulations or/and get data or measurements from the DOM.
  • Use useEffect when you don't.
Share this post