diff --git a/packages/hooks/use-debounce/src/index.ts b/packages/hooks/use-debounce/src/index.ts index be3ad47..5ad03bd 100644 --- a/packages/hooks/use-debounce/src/index.ts +++ b/packages/hooks/use-debounce/src/index.ts @@ -1,5 +1,17 @@ -type UseDebounce = () => void; +import { useEffect, useState } from 'react'; -export const useDebounce: UseDebounce = () => { - return {}; -}; +export function useDebounce(value: T, delay = 500): T { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timeoutId = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(timeoutId); + }; + }, [value, delay]); + + return debouncedValue; +} diff --git a/packages/hooks/use-debounce/tests/use-debounce.test.ts b/packages/hooks/use-debounce/tests/use-debounce.test.ts index f99bb92..fc6aa99 100644 --- a/packages/hooks/use-debounce/tests/use-debounce.test.ts +++ b/packages/hooks/use-debounce/tests/use-debounce.test.ts @@ -1,8 +1,39 @@ import { renderHook, act } from '@testing-library/react'; import { useDebounce } from '../src'; -describe('useDebounce', () => { - it('should be defined', () => { - expect(0).toBe(0); +describe('useDebounce test:', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('should update the debounced value after the specified delay', () => { + const { result, rerender } = renderHook( + ({ value }) => useDebounce(value, 1000), + { + initialProps: { value: 'initial' } + } + ); + + expect(result.current).toBe('initial'); + + act(() => { + rerender({ value: 'updated' }); + }); + + act(() => { + jest.advanceTimersByTime(500); + }); + + expect(result.current).toBe('initial'); + + act(() => { + jest.advanceTimersByTime(500); + }); + + expect(result.current).toBe('updated'); }); });