DOMの更新直後、ブラウザが描画する前に同期的に副作用を実行する。DOMのサイズ計測やスクロール位置調整に使う。
useLayoutEffect(setup, dependencies?)
useLayoutEffect(() => {
const height = ref.current?.getBoundingClientRect().height ?? 0;
setHeight(height); // 描画前に確定させる
}, []);import { useRef, useLayoutEffect, useState } from 'react';
function Tooltip({ text }: { text: string }) {
const ref = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState({ top: 0, left: 0 });
// 描画前にDOMサイズを測定して位置を確定
useLayoutEffect(() => {
if (!ref.current) return;
const rect = ref.current.getBoundingClientRect();
setPosition({
top: rect.bottom + 8,
left: rect.left,
});
}, []);
return (
<div ref={ref}>
ホバー要素
<div style={{ position: 'fixed', ...position }}>
{text}
</div>
</div>
);
}SSRではuseLayoutEffectは実行されず警告が出る。SSRとCSRの両方で動かしたい場合はuseEffectを使うか、useIsomorphicLayoutEffectパターンを使う。