/[sudobot]/trunk/docs/hooks/useDebouncedState.ts
ViewVC logotype

Contents of /trunk/docs/hooks/useDebouncedState.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 575 - (show annotations)
Mon Jul 29 17:59:26 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 734 byte(s)
chore: add trunk
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 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26