react-use/docs/useRafLoop.md
xobotyi baa2f7511e
feat(useRafLoop): reworked the hook, now it do not re-render parent component.
BREAKING CHANGE: changed return array, now it returns only functions in next order: [stop, start, isActive].

Parent component is not re-rendered on loop start/stop.
2020-04-01 10:43:31 +03:00

1.6 KiB

useRafLoop

This hook call given function within the RAF loop without re-rendering parent component. Loop stops automatically on component unmount.

Additionally hook provides methods to start/stop loop and check current state.

Usage

import * as React from 'react';
import { useRafLoop, useUpdate } from 'react-use';

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

  const [loopStop, loopStart, isActive] = useRafLoop((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>
  );
};

Reference

const [stopLoop, startLoop, isActive] = useRafLoop(callback: FrameRequestCallback, initiallyActive = true);
  • callback: (time: number)=>void — function to call each RAF tick.
    • time: number — DOMHighResTimeStamp, which indicates the current time (based on the number of milliseconds since time origin).
  • initiallyActive: boolean — whether loop should be started at initial render.
  • Return
    • stopLoop: ()=>void — stop loop if it is active.
    • startLoop: ()=>void — start loop if it was inactive.
    • isActive: ()=>booleantrue if loop is active.