Skip to content

useDebounce

Hook to delay a function execution with possibility to cancel execution and to invoke them immediately.

Demo

INFO

The component has:

  • A state internal state.
  • A toggle internal state used to choice which function execute on the OnChange event of the input element.
  • A useDebounce hook that receives a function that updates state variable with input element value and a delay of 1000ms. It returns the debounced function fn, the function to cancel debounced function execution cancel and the function to immediately execute function immediate.
  • A useCallback setted as Onchange function of the input element that executes fn or immediate to handle onChange, by toggle value.
Loading demo…
Show source code
tsx
import { BaseSyntheticEvent, useCallback, useState } from "react"
import { useDebounce } from "../../../..";

export const UseDebounce = () => {
	const [state, setState] = useState("");
	const [toggle, setToggle] = useState(true);
	const [fn, cancel, immediate] = useDebounce(
		useCallback((e: BaseSyntheticEvent) => setState(e.target.value), []),
		{
			delay: 1000
		}
	);

	const onChange = useCallback((e: BaseSyntheticEvent) => {
		toggle
			? fn(e)
			: immediate(e)
	}, [fn, immediate, toggle]);

	return (<div>
		<p>State is: {state}</p>
		<div style={{ display: "grid", gridTemplateColumns: "auto auto auto", justifyContent: "center", gap: 50 }}>
			<input type="text" onChange={onChange} />
			<button onClick={cancel}>Cancel</button>
			<button onClick={() => setToggle(t => !t)}>{toggle ? "Active immediate" : "Active debounced"}</button>
		</div>
	</div>);
}

Types

UseDebounceOpts

Options used by useDebounce.

PropertyTypeRequiredDescription
delaynumberDelay in milliseconds before the debounced function is invoked.
focusedWindowbooleanWhen true, uses requestAnimationFrame as the timer mechanism instead of setTimeout. Only fires when the browser window is focused. Useful for animation-related debouncing.

UseDebounceFunction

  • @template T Type of the parameters function.

Function used by useDebounce.

InputInput DescriptionReturnReturn Description
(...args: T)Function used by useDebounce.void;

UseDebounceResult

  • @template T Type of the UseDebounceFunction parameters function.

Result tuple by useDebounce.

IndexTypeDescription
[0](...args: T) => voidthe debounced version of the function; calling it resets the delay timer.
[1]() => voidcancel any pending invocation without calling the function.
[2](...args: T) => voidflush: execute the function immediately, cancelling the pending debounced call.

Released under the MIT License.