Skip to content

Instantly share code, notes, and snippets.

@codemile
Last active December 30, 2021 20:17
Show Gist options
  • Save codemile/749dfc01c5f4a0a0ec84522619de0de6 to your computer and use it in GitHub Desktop.
Save codemile/749dfc01c5f4a0a0ec84522619de0de6 to your computer and use it in GitHub Desktop.
A interval hook you can use in your ReactJS projects
import {DependencyList, useEffect, useMemo} from 'react';
export const useInterval = (
callback: () => void,
ms: number,
deps: DependencyList
) => {
const all_deps = useMemo(
() => [callback, ms, ...deps],
// eslint-disable-next-line react-hooks/exhaustive-deps
[callback, ms, deps]
);
useEffect(() => {
const id = setInterval(() => callback(), ms);
return () => clearInterval(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, all_deps);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment