useLayoutEffect - rs-hash/Learning GitHub Wiki

  1. 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 useLayoutEffect hook 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 the width state based on the current element's offset width.

⚠️ **GitHub.com Fallback** ⚠️