useLayoutEffect hook

How to use the useLayoutEffect hook to create layout effect.


Description

The useLayoutEffect hook works exactly like the useEffect hook, with only one exception: unlike useEffect, it works synchronously, meaning that the effect will be executed immediately after the render operations, and not when the browser's call stack is empty. This is quite useful when you want to see instant changes in your UI when something happens in your component.

Note: The fact that that the useLayoutEffect callback runs synchronously doesn't mean it will be executed "inline". The callback function will still be executed when the component already finished rendering a first time.

Using the useLayoutEffect hook will make your component take more time to render and will delay the moment where you can see visual changes in your component, especially with heavy operations. Use it only when strictly necessary and with caution.


Usage

useLayoutEffect(effectFn, dependencies);

The useLayoutEffect hook accepts an effect callback function and a list of dependencies. The effect function will be executed after the first render and whenever one of the listed dependencies changes.

For more, check the useEffect hook documentation.