Skip to content

Latest commit

Β 

History

History
35 lines (26 loc) Β· 869 Bytes

useRafLoop.md

File metadata and controls

35 lines (26 loc) Β· 869 Bytes

useRafLoop

React hook that calls given function inside the RAF loop without re-rendering parent component if not needed. Loop stops automatically on component unmount.
Provides controls to stop and start loop manually.

Usage

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

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

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

  return (
    <div>
      <div>RAF triggered: {ticks} (times)</div>
      <br />
      <button onClick={isActive ? loopStop : loopStart}>{isActive ? 'STOP' : 'START'}</button>
    </div>
  );
};

Reference

const [stopLoop, isActive, startLoop] = useRafLoop(callback: CallableFunction, deps?: DependencyList);
  • callback β€” function to call each RAF tick