javascript / intermediate
Snippet
Synchronous Layout with useLayoutEffect
useLayoutEffect runs synchronously after all DOM mutations but before the browser has a chance to paint. This is essential for measuring elements and making adjustments to avoid visual flickering.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
function Tooltip({ text }) {const [height, setHeight] = useState(0);const ref = useRef(null);useLayoutEffect(() => {const rect = ref.current.getBoundingClientRect();setHeight(rect.height);}, [text]);return <div ref={ref} style={{ top: -height }}>{text}</div>;}
react
Breakdown
1
useLayoutEffect(() => { ... }, [text]);
Executes logic after the DOM updates but before the repaint.
2
ref.current.getBoundingClientRect();
Measures the size and position of the DOM element synchronously.