跳转到主要内容

useInsertionEffect

为样式插入提供更早的时机,主要面向库作者。普通应用代码通常不需要它。

LibraryAdvanced

类型签名

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

参数与返回

  • effect:插入样式的逻辑,可以返回清理函数。
  • deps:可选依赖数组,决定何时重新插入。
  • 返回值:void。

版本与稳定性

  • 稳定性:稳定(但主要面向库作者)。
  • 应用代码建议:优先使用 useEffect/useLayoutEffect。

关键用法

TypeScript
import { useInsertionEffect } from 'react';

// 片段示例:CSS-in-JS 库内部可能会用它来插入 style 标签
export function useInjectStyle(cssText: string) {
  useInsertionEffect(() => {
    const style = document.createElement('style');
    style.textContent = cssText;
    document.head.appendChild(style);
    return () => style.remove();
  }, [cssText]);
}

相关链接

useInsertionEffect - React API 参考 - React 文档