Skip to main content

useRafFn

Call function on every requestAnimationFrame. With controls of pausing and resuming

Usage

Live Editor

function Demo() {
  const [ticks, setTicks] = useState(0);
  const [lastCall, setLastCall] = useState(0);
  const update = useUpdate();

  const [loopStop, loopStart, isActive] = useRafFn((time) => {
    setTicks(ticks => ticks + 1);
    setLastCall(time);
  });

  return (
    <div>
      <div>RAF triggered: {ticks} (times)</div>
      <div>Last high res timestamp: {lastCall}</div>
      <br />
      <button
        onClick={() => {
          isActive() ? loopStop() : loopStart();
          update();
        }}
      >
        {isActive() ? "STOP" : "START"}
      </button>
    </div>
  );
};

Result
Loading...

API

useRafFn

Returns

readonly [() => void, () => void, () => boolean]: A tuple with the following elements:

  • stop function
  • start function whether function is running

Arguments

ArgumentDescriptionTypeDefaultValue
callbackcallbackFrameRequestCallback (Required)-
initiallyActiveimmediatly startboolean | undefined-