Skip to content

Commit

Permalink
feat: add useDebounce hook
Browse files Browse the repository at this point in the history
  • Loading branch information
immois committed Nov 22, 2023
1 parent 195bb28 commit daff141
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
20 changes: 16 additions & 4 deletions packages/hooks/use-debounce/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
type UseDebounce = () => void;
import { useEffect, useState } from 'react';

export const useDebounce: UseDebounce = () => {
return {};
};
export function useDebounce<T>(value: T, delay = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);

useEffect(() => {
const timeoutId = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(timeoutId);
};
}, [value, delay]);

return debouncedValue;
}
37 changes: 34 additions & 3 deletions packages/hooks/use-debounce/tests/use-debounce.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});

0 comments on commit daff141

Please sign in to comment.