add custom useDebouncedValue hook to handle initial set value

This commit is contained in:
jeffvli
2026-01-24 17:42:53 -08:00
parent ee145d6f65
commit f786da52bb
+46 -2
View File
@@ -1,3 +1,47 @@
import { useDebouncedValue as useDebouncedValueMantine } from '@mantine/hooks';
import { useEffect, useRef, useState } from 'react';
export const useDebouncedValue = useDebouncedValueMantine;
interface UseDebouncedValueOptions {
waitForInitial?: boolean;
}
export function useDebouncedValue<T>(
value: T,
delay: number,
options?: UseDebouncedValueOptions,
): [T | undefined] {
const { waitForInitial = false } = options || {};
const [debouncedValue, setDebouncedValue] = useState<T | undefined>(
waitForInitial ? undefined : value,
);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
// Clear any existing timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Set up a new timeout to update the debounced value
timeoutRef.current = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cleanup function to clear the timeout if the component unmounts or value changes
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [value, delay]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return [debouncedValue];
}