Difference between useEffect() and useLayoutEffect()

Difference between useEffect() and useLayoutEffect()

·

1 min read

Render means computing the styles for each DOM node.
Paint means content is displayed/updated on the screen.

With that in mind, let's see what the react docs say about these hooks.

useEffect(callback)

The function passed to the useEffect will run after the render is committed to the screen.

useLayoutEffect(callback)

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

Simply put, useEffect callback() runs after the content is printed/painted on the screen. This also means that the callback does not block browser painting. The effect is triggered asynchronously but certainly before the next render.

useEffect.png

Whereas for useLayoutEffect(), the effect is fired as soon component is rendered. This means, browser is yet to paint the screen with new/modified content. Avoid using useLayoutEffect, as it is blocking and there will be a performance hit.

useLayoutEffect.png

Other than the time of firing the callback(), the two hooks are same.

When to use useLayoutEffect()??

When your component seems to flicker when the state is updated because callback is making visual changes to the DOM right after the component is painted, you should use useLayoutEffect.