Skip to content

Commit

Permalink
Add useDebounce hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathaniel81 committed May 12, 2024
1 parent 92a3fd3 commit 8e5ceb1
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions backend/frontend/src/hooks/useDebounce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useEffect, useState } from "react";

// https://codesandbox.io/s/react-query-debounce-ted8o?file=/src/useDebounce.js
export default function useDebounce(value, delay) {
// 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);
};
}, [value, delay]); // Only re-call effect if value or delay changes

return debouncedValue;
}

0 comments on commit 8e5ceb1

Please sign in to comment.