import { useEffect } from 'react'

export default (callback: () => void, shouldRun: boolean = true) => {
  useEffect(() => {
    if (!shouldRun) return;

    let frame: ReturnType<typeof requestAnimationFrame>;
    const run = () => {
      callback();
      frame = requestAnimationFrame(run);
    }

    run();
    return () => cancelAnimationFrame(frame);
  }, [callback, shouldRun])
};
