beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
47 lines (46 loc) • 1.54 kB
JavaScript
import { useCallback, useEffect, useRef, useState } from 'react';
import isFunction from './shared/isFunction';
const defaultOptions = {
cancelOnUnmount: true
};
/**
* An async-utility hook that accepts a callback function and a delay time (in milliseconds), then repeats the
* execution of the given function by the defined milliseconds.
*/
const useInterval = (fn, milliseconds, options = defaultOptions) => {
const opts = Object.assign(Object.assign({}, defaultOptions), (options || {}));
const timeout = useRef();
const callback = useRef(fn);
const [isCleared, setIsCleared] = useState(false);
// the clear method
const clear = useCallback(() => {
if (timeout.current) {
setIsCleared(true);
clearInterval(timeout.current);
}
}, []);
// if the provided function changes, change its reference
useEffect(() => {
if (isFunction(fn)) {
callback.current = fn;
}
}, [fn]);
// when the milliseconds change, reset the timeout
useEffect(() => {
if (typeof milliseconds === 'number') {
timeout.current = setInterval(() => {
callback.current();
}, milliseconds);
}
// cleanup previous interval
return clear;
}, [milliseconds]);
// when component unmount clear the timeout
useEffect(() => () => {
if (opts.cancelOnUnmount) {
clear();
}
}, []);
return [isCleared, clear];
};
export default useInterval;