Skip to content

Instantly share code, notes, and snippets.

@soker90
Last active June 21, 2022 07:11
Show Gist options
  • Save soker90/8a7cece62b0e936f487c3fbf509cb30e to your computer and use it in GitHub Desktop.
Save soker90/8a7cece62b0e936f487c3fbf509cb30e to your computer and use it in GitHub Desktop.
Debounce hook
import { useEffect } from "react";
import { useDebounce } from "hooks";
const App = () => {
const debounce = useDebounce();
useEffect(() => {
debounce(() => {
console.log('Hello world')
}, 1000);
}, []);
return null;
}
export default App;
import { act, renderHook } from "@testing-library/react-hooks";
import useDebounce from "./useDebounce";
describe("useDebounce", () => {
let debounceFunc: any;
beforeEach(() => {
const { result } = renderHook(() => useDebounce());
debounceFunc = result.current;
});
test("Not be called ", () => {
const myfunc = jest.fn();
act(() => {
debounceFunc(myfunc, 10);
});
expect(myfunc).not.toBeCalled();
});
test("Have been called ", () => {
const myfunc = jest.fn();
act(() => {
debounceFunc(myfunc, 2);
});
setTimeout(() => {
expect(myfunc).toHaveBeenCalledTimes(1);
}, 5);
});
test("Have been called onle 1 time ", () => {
const myfunc = jest.fn();
act(() => {
debounceFunc(myfunc, 2);
debounceFunc(myfunc, 2);
debounceFunc(myfunc, 2);
});
setTimeout(() => {
expect(myfunc).toHaveBeenCalledTimes(1);
}, 10);
});
});
import { useState } from "react";
export default function useDebounce() {
const [debounceHandler, setDebounceHandler] = useState<number | null>(null);
const debounceFunc = (func: (...args: any[]) => void, delay: number) => {
if (debounceHandler) clearTimeout(debounceHandler);
const timeout = setTimeout(func, delay);
setDebounceHandler(Number(timeout));
};
return debounceFunc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment