apps/mantine.dev/src/pages/hooks/use-debounced-callback.mdx
import { UseDebouncedCallbackDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';
export default Layout(MDX_DATA.useDebouncedCallback);
The use-debounced-callback hook creates a debounced version of the given function,
delaying its execution until a specified time has elapsed since the last invocation.
By default, the callback is not fired when the component unmounts.
If you want to execute the pending callback before the component unmounts,
set flushOnUnmount: true:
import { useDebouncedCallback } from '@mantine/hooks';
const callback = useDebouncedCallback(
() => console.log('Hello'),
{ delay: 1000, flushOnUnmount: true },
);
Set leading: true to execute the callback immediately on the first call,
then ignore subsequent calls within the delay window:
import { useDebouncedCallback } from '@mantine/hooks';
const callback = useDebouncedCallback(
() => console.log('Hello'),
{ delay: 1000, leading: true },
);
Use maxWait to guarantee the callback is executed at least once within the given time
window, even if calls keep arriving. This is useful for scenarios like search-as-you-type
where you want intermediate results during continuous input:
import { useDebouncedCallback } from '@mantine/hooks';
const callback = useDebouncedCallback(
(query: string) => fetchResults(query),
{ delay: 300, maxWait: 1000 },
);
You can call the flush method to execute the debounced callback immediately,
or cancel to discard the pending call:
import { useDebouncedCallback } from '@mantine/hooks';
const callback = useDebouncedCallback(() => console.log('Hello'), 1000);
callback.flush(); // immediately executes the pending callback
callback.cancel(); // discards the pending callback
callback.isPending(); // returns true if a call is waiting to execute
interface UseDebouncedCallbackOptions {
delay: number;
flushOnUnmount?: boolean;
leading?: boolean;
maxWait?: number;
}
type UseDebouncedCallbackReturnValue<T extends (...args: any[]) => any> = ((
...args: Parameters<T>
) => void) & { flush: () => void; cancel: () => void; isPending: () => boolean };
function useDebouncedCallback<T extends (...args: any[]) => any>(
callback: T,
delayOrOptions: number | UseDebouncedCallbackOptions
): UseDebouncedCallbackReturnValue<T>
The UseDebouncedCallbackOptions and UseDebouncedCallbackReturnValue types are exported from the @mantine/hooks package;
you can import them in your application:
import type { UseDebouncedCallbackOptions, UseDebouncedCallbackReturnValue } from '@mantine/hooks';