javascript / intermediate
Snippet
Measuring DOM Nodes with useLayoutEffect
useLayoutEffect fires synchronously after all DOM mutations but before the browser has a chance to paint. It is used to read layout from the DOM and synchronously re-render to avoid visual flickering.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { useState, useLayoutEffect, useRef } from 'react';function Tooltip() {const [width, setWidth] = useState(0);const elRef = useRef();useLayoutEffect(() => {setWidth(elRef.current.getBoundingClientRect().width);}, []);return <div ref={elRef}>Width: {width}px</div>;}
react
Breakdown
1
useLayoutEffect(() => { ... }, []);
Runs before the screen is painted, allowing for synchronous layout adjustments.
2
elRef.current.getBoundingClientRect().width
Reads the precise physical dimensions of the element from the browser.