@patreon/studio
Version:
Patreon Studio Design System
42 lines • 1.51 kB
JavaScript
import { useEffect, useRef } from 'react';
/**
* Use this hook to schedule a dynamic callback. The callback can be updated
* without affecting the timer. Additionally, if the delay or any other passed
* dependencies are shallowly mutated, the timer is restarted.
*
* For a detailed explanation of how this works, see Dan Abramov’s
* [article](https://overreacted.io/making-setinterval-declarative-with-react-hooks/).
*/
export function useTimeout(
/**
* Function to call when delay elapses. Can be mutated on subsequent render
* calls without affecting the timeout.
*/
callback,
/**
* Timeout delay, in milliseconds. If mutated, the timeout is restarted. If set
* to null, the existing timeout is canceled.
*/
delay,
/**
* If any of the dependencies in this array are mutated, the timeout is restarted.
*/
dependencies = []) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// TODO (legacied consistent-return)
// This failure is legacied in and should be updated. DO NOT COPY.
// eslint-disable-next-line consistent-return
useEffect(() => {
function useTimeoutCallbackThunk() {
savedCallback.current?.();
}
if (delay !== null) {
const id = setTimeout(useTimeoutCallbackThunk, delay);
return () => clearTimeout(id);
}
}, [delay, ...dependencies]); // eslint-disable-line react-hooks/exhaustive-deps
}
//# sourceMappingURL=index.js.map