Skip to content

Commit

Permalink
feat(react): add useDebounce hook
Browse files Browse the repository at this point in the history
  • Loading branch information
hckhanh committed Mar 30, 2021
1 parent 5ef6bf4 commit 50caa6a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
43 changes: 43 additions & 0 deletions packages/trakas-react/__tests__/hooks/useDebounce.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { act, render, screen } from "@testing-library/react";
import { useEffect, useState } from "react";
import { useDebounce } from "../../src/hooks/useDebounce";

function TestComponent() {
const [value, setValue] = useState("1");
const debounceValue = useDebounce(value, 3000);

useEffect(() => {
setTimeout(() => {
setValue("2");
}, 2000);
}, []);

return <div>{debounceValue}</div>;
}

describe("useDebounce", () => {
beforeEach(() => {
jest.useFakeTimers();
});

test("not updates value within 5s", async () => {
render(<TestComponent />);
act(() => {
jest.advanceTimersByTime(4000);
});

const textElement = screen.queryByText("2");
expect(textElement).toBeNull();
});

test("updates value after 5s", async () => {
render(<TestComponent />);
act(() => {
jest.advanceTimersByTime(5000);
});

const textElement = await screen.findByText("2");
expect(textElement).not.toBeNull();
expect(textElement).toBeInTheDocument();
});
});
16 changes: 16 additions & 0 deletions packages/trakas-react/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useEffect, useState } from "react";

export function useDebounce<T = undefined>(value: T | undefined, delay: number): T | undefined {
const [debouncedValue, updateDebounceValue] = useState(value);

useEffect(() => {
const handler = setTimeout(() => {
updateDebounceValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}
1 change: 1 addition & 0 deletions packages/trakas-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./hooks/useToggle";
export * from "./hooks/useDebounce";

0 comments on commit 50caa6a

Please sign in to comment.