JAVASCRIPT
Accurately Measure DOM Layout with `useLayoutEffect`
Learn to use `useLayoutEffect` in React for synchronous DOM updates and measurements, crucial for preventing visual glitches when layout changes depend on computations.
import React, { useState, useLayoutEffect } from 'react';
function MeasuringComponent() {
const [height, setHeight] = useState(0);
const elementRef = React.useRef(null);
useLayoutEffect(() => {
if (elementRef.current) {
// Synchronously measure the DOM element after all DOM mutations
setHeight(elementRef.current.offsetHeight);
console.log('Element height (useLayoutEffect):', elementRef.current.offsetHeight);
}
}, []); // Run once on mount
return (
<div ref={elementRef} style={{ border: '1px solid blue', padding: '10px', margin: '20px' }}>
<p>This is a dynamically sized content block.</p>
<p>Its height is: {height}px</p>
{/* Simulate content that might affect layout */}
{Array(Math.floor(Math.random() * 5) + 1).fill().map((_, i) => <p key={i}>Line {i + 1}</p>)}
</div>
);
}
How it works: `useLayoutEffect` is similar to `useEffect` but fires synchronously after all DOM mutations but *before* the browser paints. This makes it ideal for reading layout from the DOM and synchronously re-rendering. In this snippet, it's used with `useRef` to measure the `offsetHeight` of an element immediately after the browser has calculated its layout, ensuring that the measurement is accurate and any state updates based on it won't cause visual flickering.