← React Beginner Questions - Set 6 Q58
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.
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>;
}