1 |
import { useRef, useState } from "react"; |
2 |
|
3 |
export default function useDebouncedState<T>(data?: T, delay = 1500) { |
4 |
const [state, setState] = useState<T>(data as T); |
5 |
const [queued, setQueued] = useState(false); |
6 |
const timeoutRef = useRef<NodeJS.Timeout | undefined>(); |
7 |
|
8 |
const setDebouncedState = (newData: T) => { |
9 |
if (!queued) { |
10 |
setQueued(true); |
11 |
} |
12 |
|
13 |
if (timeoutRef.current) { |
14 |
clearTimeout(timeoutRef.current); |
15 |
timeoutRef.current = undefined; |
16 |
} |
17 |
|
18 |
timeoutRef.current = setTimeout(() => { |
19 |
setState(newData); |
20 |
setQueued(false); |
21 |
}, delay); |
22 |
}; |
23 |
|
24 |
return [state as T, queued, setDebouncedState, setState] as const; |
25 |
} |