aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/interval.js
blob: 78f6e7b286fd63d8d1268fee70611b1805fc0802 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { useEffect, useRef } from "react";

const useInterval = (callback, interval, immediate) => {
    const ref = useRef();
    useEffect(() => {
      ref.current = callback;
    }, [callback]);

    useEffect(() => {
      let cancelled = false;

      const fn = () => {
        ref.current(() => cancelled);
      };

      const id = setInterval(fn, interval);
      if (immediate) fn();

      return () => {
        cancelled = true;
        clearInterval(id);
      };
    }, [interval, immediate]);
  };

  export default useInterval;