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.
| Property | Type | Required | Description |
|---|---|---|---|
delay | number | ✓ | Delay in milliseconds before the debounced function is invoked. |
focusedWindow | boolean | When true, uses requestAnimationFrame as the timer mechanism instead of setTimeout. Only fires when the browser window is focused. Useful for animation-related debouncing. |
UseDebounceFunction
@templateT Type of the parameters function.
Function used by useDebounce.
| Input | Input Description | Return | Return Description |
|---|---|---|---|
(...args: T) | Function used by useDebounce. | void; |
UseDebounceResult
@templateT Type of the UseDebounceFunction parameters function.
Result tuple by useDebounce.
| Index | Type | Description |
|---|---|---|
[0] | (...args: T) => void | the debounced version of the function; calling it resets the delay timer. |
[1] | () => void | cancel any pending invocation without calling the function. |
[2] | (...args: T) => void | flush: execute the function immediately, cancelling the pending debounced call. |
