Skip to content

Commit

Permalink
feat: add useDebounce hook
Browse files Browse the repository at this point in the history
  • Loading branch information
m.gharouni committed Dec 8, 2021
1 parent f8187c9 commit 155a7c7
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/core/src/hooks/useDebounce/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useEffect, useState } from "react";

function useDebounce<T extends any[]>(delay: number, ...value: T): T {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(
() => {
// Update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

// Cancel the timeout if value changes (also on delay change or unmount)
// This is how we prevent debounced value from updating if value is changed ...
// .. within the delay period. Timeout gets cleared and restarted.
return () => {
clearTimeout(handler);
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[delay, ...value], // Only re-call effect if value or delay changes
);

return debouncedValue;
}

export { useDebounce };

0 comments on commit 155a7c7

Please sign in to comment.