← Wszystkie zadaniaReact · Senior
Hook useInterval
Napisz hook useInterval(callback, delay), który wywołuje callback co delay milisekund, dopóki komponent jest zamontowany.
Każde wywołanie musi używać najnowszej wersji callback z aktualnymi propsami i stanem, ale nowa funkcja przy każdym renderze nie może restartować interwału. delay = null wstrzymuje interwał. Po odmontowaniu wywołań już nie ma.
Ctrl+Enter uruchamia testy. Tab robi wcięcie; aby wyjść z edytora klawiaturą, naciśnij Esc, a potem Tab. Kod zapisuje się w tej przeglądarce.
Testy (5)
const f = fn(); renderHook(() => useInterval(f, 30)); await wait(110); expect(f.calls.length >= 2 && f.calls.length <= 4).toBe(true);
const log = []; const { rerender } = renderHook(({ n }) => useInterval(() => log.push(n), 30), { initialProps: { n: 1 } }); await wait(45); rerender({ n: 2 }); await wait(50); expect(log[0]).toBe(1); expect(log[log.length - 1]).toBe(2);
const f = fn(); const { rerender } = renderHook(() => useInterval(() => f(), 40)); for (let i = 0; i < 6; i++) { await wait(15); rerender(); } expect(f.calls.length >= 1).toBe(true);
const f = fn(); renderHook(() => useInterval(f, null)); await wait(60); expect(f).toHaveBeenCalledTimes(0);
const f = fn(); const { unmount } = renderHook(() => useInterval(f, 20)); unmount(); await wait(60); expect(f).toHaveBeenCalledTimes(0);