The useLayoutEffect
hook in React is similar to the useEffect
hook, but it runs synchronously after all DOM mutations are applied. It allows you to perform imperative operations that rely on the updated DOM layout before the browser paints the screen.
Here's a concise explanation of the useLayoutEffect
hook:
useLayoutEffect
is a React hook that runs after the DOM has been updated but before the browser paints the screen.It has the same API as
useEffect
, which means you can provide a callback function as the first argument.The difference is that
useLayoutEffect
runs synchronously and blocks the painting process until it's finished.This makes it suitable for tasks that require accurate measurements or immediate DOM updates.
However, you should use
useEffect
in most cases since it doesn't block painting and is more performant.Only use
useLayoutEffect
when you need to interact with the updated layout before it's rendered.
Here is an example:
import React, { useState, useLayoutEffect } from 'react';
function ExampleComponent() {
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
function updateWidth() {
setWidth(window.innerWidth);
}
// Add event listener to update width when the window is resized
window.addEventListener('resize', updateWidth);
// Call the update function once to get the initial width
updateWidth();
// Clean up the event listener when the component unmounts
return () => {
window.removeEventListener('resize', updateWidth);
};
}, []); // Empty dependency array ensures the effect runs only once
return (
<div>
Window width: {width}px
</div>
);
}
In this example, the useLayoutEffect
hook is used to update the width
state variable whenever the window is resized. It first defines an updateWidth
function that retrieves the current window width and updates the state.
Inside useLayoutEffect
, an event listener is added to the resize
event, which calls the updateWidth
function. This ensures that the width is updated whenever the window is resized.
The effect also includes a cleanup function that removes the event listener when the component unmounts. This is important to prevent memory leaks.
Finally, the component renders the width
value, which reflects the current window width.