Skip to main content

useOnceLayoutEffect

A Hook that avoids React18 useLayoutEffect run twice

Usage

Live Editor

function Demo() {
  const [updateEffect, setLayoutEffect] = useState(0);
  const [onceLayoutEffect, setOnceLayoutEffect] = useState(0);

  useOnceLayoutEffect(() => {
    setOnceLayoutEffect(onceEffect => onceEffect + 1);
  }, []);

  useLayoutEffect(() => {
    setLayoutEffect(effect => effect + 1);
  }, []);

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

Result
Loading...