Elffuss BraidHub

kikocis/continue public

main · 1.0 KiBRawPermalink
1import { useEffect, useRef, useState } from "react";
2
3export function useDebounceValue<T>(value: T, delay: number = 500): T {
4 const [debouncedValue, setDebouncedValue] = useState<T>(value);
5
6 useEffect(() => {
7 const timer = setTimeout(() => {
8 setDebouncedValue(value);
9 }, delay);
10
11 return () => {
12 clearTimeout(timer);
13 };
14 }, [value, delay]);
15
16 return debouncedValue;
17}
18
19export function useDebouncedEffect(
20 effect: () => void,
21 delay: number,
22 deps: unknown[],
23) {
24 const timeoutRef = useRef<NodeJS.Timeout | null>(null);
25 const callBackRef = useRef(() => {});
26
27 useEffect(() => {
28 // do not want the timeout to reset on effect dep change
29 callBackRef.current = effect;
30 }, [effect]);
31
32 useEffect(() => {
33 if (timeoutRef.current) {
34 clearTimeout(timeoutRef.current);
35 }
36
37 timeoutRef.current = setTimeout(() => {
38 callBackRef.current();
39 }, delay);
40
41 return () => {
42 if (timeoutRef.current) {
43 clearTimeout(timeoutRef.current);
44 }
45 };
46 }, [delay, ...deps]);
47}