useLayoutEffect - rs-hash/Learning GitHub Wiki
-
useLayoutEffect:
- Description: useLayoutEffect is similar to useEffect, but it runs synchronously after the DOM has been updated but before the browser paints.
- Example:
import React, { useState, useLayoutEffect } from 'react'; function MeasureElement() { const [width, setWidth] = useState(0); const ref = useRef(null); useLayoutEffect(() => { setWidth(ref.current.offsetWidth); }, []); return <div ref={ref}>Width: {width}px</div>; }
Explanation: In the example above, the
useLayoutEffecthook is used to measure the width of an element after it has been rendered. The effect runs once (due to the empty dependency array[]) and sets thewidthstate based on the current element's offset width.