useLayoutEffect
Learn how to read layout from the DOM and synchronously re-render.
We'll cover the following
What is the useLayoutEffect()
method?
We briefly mentioned useLayoutEffect()
when we presented useEffect()
. It follows a
similar pattern as the useEffect()
Hook but differs in the timing of its execution and its synchronous nature.
While useEffect()
is executed with a little bit of delay after the layout and paint phase of the browser, useLayoutEffect()
is executed after layout but before paint. This difference in the timing allows useLayoutEffect()
to read the current layout from the DOM and change it before it is displayed in the browser.
This kind of behavior is similar to what was previously achieved by componentDidMount()
or componentDidUpdate()
in class components. Due to performance reasons, however, we’ll use useEffect()
in most cases and only use useLayoutEffect()
if we know
exactly what we’re doing. TheuseLayoutEffect()
method can also help if we are struggling to migrate class components to function components due to the different timings of the effects.
Note: Neither
useEffect()
noruseLayoutEffect()
will be executed server-side. While this does not pose a problem foruseEffect()
Since it is only executed after the layout and painting phase of the browser,useLayoutEffect()
might lead to differences in the server-side rendered markup compared to the initial client-side render. React will usually inform us of these differences and create a warning in the console. In these cases,useEffect()
should be used instead or components usinguseLayoutEffect()
should be mounted after the browser’s paint phase.
Code Example
Let’s look at an example:
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const [mountLayoutComp, setMountLayoutComp] = useState(false);
useEffect(() => {
setMountLayoutComp(true);
}, []);
return mountLayoutComp ? <ComponentWithLayoutEffect /> : null;
};
ReactDOM.render(<App />, document.getElementById('root'));
In this example, the component using useLayoutEffect()
is only registered after the component is mounted. We achieve this by checking for the mountLayoutComp
state after the first paint phase.
Get hands-on with 1200+ tech skills courses.