Member-only story

Performant React 101: The difference between `useEffect` and `useLayoutEffect`

JW
3 min readMay 29, 2022

--

Photo by Kaspars Eglitis on Unsplash

As front-end developers working with React, we use the useEffect hook all the time to render side-effects.

But did you know that there is a similar but slightly different hook called useLayoutEffect ? I didn’t, until I stumbled on an instance of this used in one of the codebases I was contributing to.

This is a blog to get to the heart of the difference between the two and understand when and when not to use each.

The difference

In a nutshell the difference is about precision.

  • useEffect runs but there is no guarantee about exactly when this occurs. It is an asynchronous operation that runs after layout and painting of the pixels.
  • useLayoutEffect in contrast, is guaranteed to run immediately. It is a synchronous operation that occurs after all DOM mutations and before the browser can paint the pixels. If you are familiar with the componentDidMount lifecycle in React’s class components, this is basically the equivalent behaviour.

useLayoutEffect seems superior. Should we use it for everything?

But why, if all else being equal wouldn’t we want to use useLayoutEffect all the time?

--

--

JW
JW

Written by JW

Front-End Software Engineer, and avid learner of history.

No responses yet