useDebounce
React hook to apply a delay to a function.
Made by lucasInstant value :
Debounced value :
import useDebounce from "@/components/targetblank/hooks/use-debounce";
import { Input } from "@/components/ui/input";
import React, { useState } from "react";
export default function DebounceDemo() {
const [value, setValue] = useState("");
const [debouncedValue, setDebouncedValue] = useState("");
const debouncedUpdate = useDebounce((val: string) => {
setDebouncedValue(val);
}, 500);
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setValue(e.target.value);
debouncedUpdate(e.target.value);
}
return (
<div className="flex flex-col gap-4 w-[400px]">
<Input
type="text"
value={value}
onChange={handleChange}
placeholder="Your entry will be debounced after 300ms"
/>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">Instant value :</span>
<span className="text-sm">{value}</span>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
Debounced value :
</span>
<span className="text-sm">{debouncedValue}</span>
</div>
</div>
</div>
);
}
Installation
Install the following dependencies:
Copy and paste the following code into your project:
import * as React from "react";
function useDebounce<T>(
callback: (...args: T[]) => void,
delay = 300,
): (...args: T[]) => void {
const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);
const debouncedCallback = React.useCallback(
(...args: T[]) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callback(...args);
}, delay);
},
[callback, delay],
);
return debouncedCallback;
}
export default useDebounce;
Update the import paths to match your project setup.
Usage
const debouncedUpdate = useDebounce((val: string) => {
setDebouncedValue(val);
}, 500);
Props
Prop | Type | Default |
---|---|---|
callback | function | - |
delay? | number | - |