The useLayoutEffect hook is similar to useEffect, but it’s executed synchronously after all DOM mutations. This makes it useful for manipulating the DOM immediately after a component is rendered.
Here’s an example of how to use useLayoutEffect to measure the size of an element:
import React, { useState, useLayoutEffect, useRef } from 'react'; function ResizableBox() { const [width, setWidth] = useState(100); const [height, setHeight] = useState(100); const boxRef = useRef(null); useLayoutEffect(() => { const handleResize = () => { setWidth(boxRef.current.clientWidth); setHeight(boxRef.current.clientHeight); }; handleResize(); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return ( <div ref={boxRef} style={{ width: '50%', height: '50%', backgroundColor: 'red' }}> <p>Width: {width}px</p> <p>Height: {height}px</p> </div> ); }
In this example, we define a ResizableBox component that uses the useLayoutEffect hook to measure the size of a div element. We then use the size values to render the width and height of the box. The hook also adds and removes a resize event listener to update the size values when the window is resized.