你不知道的React系列(二十)useLayoutEffect

95 阅读1分钟

本文正在参加「金石计划」

useLayoutEffect(setup, dependencies?)

useLayoutEffect 会影响性能,阻止浏览器重新绘制屏幕。

  • 组件挂载到 DOM 之前执行

  • 读取 DOM 布局并进行修改触发渲染

  • 初始化 state => 渲染 => useLayoutEffect => 改变 state => 组件重新渲染 => 显示 UI

function Tooltip() {
  const ref = useRef(null);
  const [tooltipHeight, setTooltipHeight] = useState(0); // You don't know real height yet

  useLayoutEffect(() => {
    const { height } = ref.current.getBoundingClientRect();
    setTooltipHeight(height); // Re-render now that you know the real height
  }, []);

  // ...use tooltipHeight in the rendering logic below...
}

问答