Last active
June 21, 2022 07:11
-
-
Save soker90/8a7cece62b0e936f487c3fbf509cb30e to your computer and use it in GitHub Desktop.
Debounce hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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