UseDebounceState
guarahooks/use-debounce-stateFreeHook
Debounce the state update.
Install it
npx shadcn@latest add https://guarahooks.com/r/use-debounce-state.jsonSource
1'use client';23import {4 SetStateAction,5 useCallback,6 useEffect,7 useRef,8 useState,9} from 'react';1011interface UseDebouncedStateOptions {12 leading?: boolean;13}1415export function useDebouncedState<T>(16 defaultValue: T,17 delay: number = 500,18 options: UseDebouncedStateOptions = {},19) {20 const [value, setValue] = useState<T>(defaultValue);21 const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);22 const leadingRef = useRef(true);2324 const clearDebounceTimeout = useCallback(() => {25 if (timeoutRef.current !== null) {26 clearTimeout(timeoutRef.current);27 timeoutRef.current = null;28 }29 }, []);3031 useEffect(() => {32 return () => {33 clearDebounceTimeout();34 };35 }, [clearDebounceTimeout]);3637 useEffect(() => {38 leadingRef.current = true;39 }, [defaultValue]);4041 const debouncedSetValue = useCallback(42 (newValue: SetStateAction<T>) => {43 clearDebounceTimeout();44 if (leadingRef.current && options.leading) {45 setValue(newValue);46 } else {47 timeoutRef.current = setTimeout(() => {48 leadingRef.current = true;49 setValue(newValue);50 }, delay);51 }52 leadingRef.current = false;53 },54 [clearDebounceTimeout, delay, options.leading],55 );5657 return [value, debouncedSetValue] as const;58}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
