CodePark/ questions / Effects
START PRACTICINGPRACTICE
Frontend question · React › Effects

What is the difference between useEffect and useLayoutEffect? When would you use the latter?

Both run after React updates the DOM. The difference is timing compared with the browser's paint, the moment the user sees the new pixels:

  • useEffect usually runs after the browser paints. So it does not block the screen from updating.
  • useLayoutEffect runs synchronously after the DOM changes but before the browser paints. Any state update inside it is also processed before paint.

Use useLayoutEffect when you need to measure layout and adjust before the user sees anything. For example, read a tooltip's height with getBoundingClientRect and move it. With useEffect, the tooltip would flicker in the wrong place for one frame.

Because it blocks painting, overusing it hurts performance. Default to useEffect. Switch only when you see a visual flicker caused by measuring after paint. Neither hook runs during server rendering.

  • useLayoutEffect runs before the browser paints and blocks the paint.
  • useEffect usually runs after paint and does not block it.
  • Use a layout effect to measure the DOM and adjust it without flicker.
  • Overusing layout effects hurts performance, so default to useEffect.
  • Neither hook runs on the server.