跳到主要内容

useOnceEffect

避免 React18 useEffect 运行两次

Usage

实时编辑器

function Demo() {
  const [effect, setEffect] = useState(0);
  const [onceEffect, setOnceEffect] = useState(0);

  useOnceEffect(() => {
    setOnceEffect(onceEffect => onceEffect + 1);
  }, []);

  useEffect(() => {
    setEffect(effect => effect + 1);
  }, []);

  return (
    <div>
      <div>onceEffect: {onceEffect}</div>
      <br />
      <div>effect: {effect}</div>
    </div>
  );
};

结果
Loading...