← React Beginner Questions - Set 6 Q58

What is the purpose of the useLayoutEffect hook?

React Beginner Questions - Set 6

Same as `useEffect`, but it runs synchronously after the DOM is updated and before the browser paints — the place to measure and correct layout.

Example

import { useLayoutEffect, useRef, useState } from 'react';

export default function Tooltip({ anchorRef, children }) {
  const tipRef = useRef(null);
  const [offset, setOffset] = useState(0);

  useLayoutEffect(() => {
    const anchor = anchorRef.current.getBoundingClientRect();
    const tip = tipRef.current.getBoundingClientRect();
    // Flip to the other side before the user ever sees it
    if (anchor.bottom + tip.height > window.innerHeight) {
      setOffset(-tip.height - anchor.height);
    }
  }, []);

  return <div ref={tipRef} style={{ transform: `translateY(${offset}px)` }}>{children}</div>;
}

What to notice

← Back to the question list