import { useRef, useEffect } from 'react';
export const useTimeout = (callback: () => unknown, delay: number, dependencies: unknown[]) => {
const timeoutRef = useRef<number>();
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
const tick = () => savedCallback.current();
timeoutRef.current = window.setTimeout(tick, delay);
return () => window.clearTimeout(timeoutRef.current);
}, [delay, ...dependencies]);
return timeoutRef;
};
import { renderHook } from '@testing-library/react';
import { useTimeout } from './useTimeout';
describe('hooks/useTimeout', () => {
it('returns useTimeout', () => {
const {result} = renderHook(() => useTimeout(() => false, 500, []));
expect(result.current).toBe(5);
});
});
- expect(result.current).toBe(5);
+ expect(result.current.current).toBe(5);