DEV Community

Cover image for React Hooks: useLayoutEffect
Abdullah Furkan Özbek
Abdullah Furkan Özbek

Posted on • Originally published at blog.furkanozbek.com

React Hooks: useLayoutEffect

1 - Definition

useLayoutEffect runs synchronously immediately after React has performed all DOM mutations.

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.

2 - Snytax

It looks exactly like useEffect but different use-cases. Here is the syntax for it;

useEffect(() => {
  // do side effects
  return () => /* cleanup */
}, [dependency, array]);

useLayoutEffect(() => {
  // do side effects
  return () => /* cleanup */
}, [dependency, array]);
Enter fullscreen mode Exit fullscreen mode

3 - useEffect vs useLayoutEffect

useEffect
(Component > State Changes > Component Renders > Rendered Component is Printed on Screen > useEffect runs)

useEffect will run after React renders your component and ensures that your effect callback does not block browser painting.

useLayoutEffect
(Component > State Changes > Component Renders > useLayoutEffect runs > Rendered Component is Printed on Screen)

useLayoutEffect runs synchronously immediately after React has performed all DOM mutations.

4 - One Possible Example

If your effect is mutating the DOM (via a node ref) and the DOM mutation will change the look of the DOM node between the time that it is rendered and your effect mutates it, then you want to 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.

5 - Summary

Try use useEffect most of the time, if you are really need to mutate dom directly go take a look similar examples first before applying useLayoutEffect.

  • useLayoutEffect: If you need to mutate the DOM and/or do need to perform measurements
  • useEffect: If you don't need to interact with the DOM at all (%99.99 of the time you will use this)

Links

Discussion (0)