apps/mantine.dev/src/pages/hooks/use-debounced-value.mdx
import { UseDebouncedValueDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';
export default Layout(MDX_DATA.useDebouncedValue);
The use-debounced-value hook debounces value changes.
This can be useful when you want to perform a heavy operation based on React state,
for example, sending a search request. Unlike use-debounced-state, it
is designed to work with controlled components.
value prop instead of defaultValue), for example, it renders on every state change like a character typed in an input.useState.You can immediately update the value with the first call using { leading: true } options:
The hook returns a third element with cancel and flush handlers.
cancel discards the pending update, flush applies it immediately.
Updates cancel automatically on component unmount.
In this example, type in some text and click the cancel button within a second to cancel debounced value change:
<Demo data={UseDebouncedValueDemos.cancel} />The second element of the returned tuple is a shorthand for cancel for backwards compatibility.
const [debounced, cancel, { cancel, flush }] = useDebouncedValue(value, 200);
interface UseDebouncedValueOptions {
leading?: boolean;
}
interface UseDebouncedValueHandlers {
cancel: () => void;
flush: () => void;
}
type UseDebouncedValueReturnValue<T> = [T, () => void, UseDebouncedValueHandlers];
function useDebouncedValue<T = any>(
value: T,
wait: number,
options?: UseDebouncedValueOptions,
): UseDebouncedValueReturnValue<T>
The UseDebouncedValueOptions and UseDebouncedValueReturnValue types are exported from the @mantine/hooks package;
you can import them in your application:
import type { UseDebouncedValueOptions, UseDebouncedValueReturnValue } from '@mantine/hooks';