JAVASCRIPT
Synchronously Measuring DOM Layout with useLayoutEffect
Use React's useLayoutEffect hook to perform DOM measurements or manipulations that must happen synchronously after mutations, ensuring accurate layout before browser paint.
import React, { useState, useRef, useLayoutEffect } from 'react';
function MeasuredDiv() {
const [height, setHeight] = useState(0);
const divRef = useRef(null);
useLayoutEffect(() => {
if (divRef.current) {
// Perform synchronous DOM measurement
setHeight(divRef.current.offsetHeight);
}
}, []); // Empty dependency array means this runs once after initial render
return (
<div ref={divRef} style={{ border: '1px solid blue', padding: '20px', margin: '20px' }}>
This div's measured height: {height}px
<p>Some dynamic content inside.</p>
<p>More content.</p>
</div>
);
}
export default MeasuredDiv;
How it works: `useLayoutEffect` is a version of `useEffect` that fires synchronously *after* all DOM mutations but *before* the browser has a chance to paint. This is crucial for situations where you need to measure a DOM element's size or position, or make synchronous DOM changes, and then use that information to prevent visual inconsistencies or "flickering" before the user sees the updated layout. Unlike `useEffect`, which runs asynchronously, `useLayoutEffect` ensures these operations complete before the next browser repaint.