UNPKG

@atlaskit/motion

Version:

A set of utilities to apply motion in your application.

31 lines (29 loc) 1.01 kB
import { useCallback, useEffect, useRef } from 'react'; import { getHookDeps } from './get-hook-deps'; // Handle both browser and Node.js environments /** * Will return set timeout as a function which will clean itself up. */ // eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports export const useSetTimeout = (opts = { cleanup: 'unmount' }) => { const timeouts = useRef([]); useEffect(() => { return () => { if (timeouts.current.length) { timeouts.current.forEach(id => clearTimeout(id)); timeouts.current = []; } }; // We dynamically set this so we either clean up on the next effect - or on unmount. // eslint-disable-next-line react-hooks/exhaustive-deps }, getHookDeps(opts)); return useCallback((handler, timeout, ...args) => { const id = setTimeout(() => { timeouts.current = timeouts.current.filter(timeoutId => timeoutId !== id); handler(); }, timeout, ...args); timeouts.current.push(id); }, []); };