Skip to content

Instantly share code, notes, and snippets.

@qborreda
Created June 6, 2019 15:16
Show Gist options
  • Select an option

  • Save qborreda/ecddece84d8f83842e2d96c528ccc80b to your computer and use it in GitHub Desktop.

Select an option

Save qborreda/ecddece84d8f83842e2d96c528ccc80b to your computer and use it in GitHub Desktop.

Revisions

  1. qborreda created this gist Jun 6, 2019.
    23 changes: 23 additions & 0 deletions useInterval
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    /**
    * React custom hook to fire a function given an interval
    * @usage: useInterval(()=>{...},1000);
    **/
    function useInterval(callback, delay) {
    const savedCallback = useRef();

    useEffect(() => {
    savedCallback.current = callback;
    });

    useEffect(
    () => {
    function tick() {
    savedCallback.current();
    }

    let id = setInterval(tick, delay);
    return () => clearInterval(id);
    },
    [delay]
    );
    }