react-use/docs/useRafLoop.md
xobotyi 322b45f36c Merge remote-tracking branch 'origin/master'
# Conflicts:
#	docs/useRafLoop.md
2019-08-03 02:15:27 +03:00

989 B

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.

2nd parameter is dependencies list as in useEffect hook.

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
  • deps - a list of dependencies, as if it was in useEffect hook.