useLayoutEffect

在浏览器绘制前同步执行副作用,用于读布局、写布局并避免闪烁。

技术规格

类型签名

TypeScript
function useLayoutEffect(
  effect: () => (void | (() => void)),
  deps?: DependencyList
): void

何时使用

  • 你需要在绘制前读取 DOM 布局(例如 getBoundingClientRect)。
  • 你需要在绘制前同步写入样式/滚动位置,避免用户看到跳动。
  • 其他大多数副作用(数据获取、订阅等)优先使用 useEffect。
TypeScript
useEffect(() => {
  const rect = ref.current.getBoundingClientRect();
  setWidth(Math.round(rect.width));
}, []);

示例:测量布局

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

export function MeasuredBox() {
  const ref = useRef<HTMLDivElement | null>(null);
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    setWidth(Math.round(rect.width));
  }, []);

  return (
    <div>
      <div ref={ref} style={{ padding: 16, border: '1px solid currentColor' }}>
        我会被测量
      </div>
      <p>宽度: {width}px</p>
    </div>
  );
}