use-debounced-value

Debounce value changes
Import

Usage

Use hook to debounce value change. This can be useful in case you want to perform a heavy operation based on react state, for example, send search request.

Value: [empty string]
Debounced value: [empty string]
import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { TextInput, Text } from '@mantine/core';
export function Demo() {
const [value, setValue] = useState('');
const [debounced] = useDebouncedValue(value, 200);
return (
<>
<TextInput
label="Enter value to see debounce"
value={value}
style={{ flex: 1 }}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<Text>Value: {value}</Text>
<Text>Debounced value: {debounced}</Text>
</>
);
}

Leading update

You can remove immediately update value with first call with { leading: true } options:

Value: [empty string]
Debounced value: [empty string]
import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { TextInput, Text } from '@mantine/core';
export function Demo() {
const [value, setValue] = useState('');
const [debounced] = useDebouncedValue(value, 200, { leading: true });
return (
<>
<TextInput
label="Enter value to see debounce"
value={value}
style={{ flex: 1 }}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<Text>Value: {value}</Text>
<Text>Debounced value: {debounced}</Text>
</>
);
}

Cancel update

Hook provides cancel callback, you can use it to cancel update. Update cancels automatically on component unmount.

In this example, type in some text and click cancel button within a minute to cancel debounced value change:

Value: [empty string]
Debounced value: [empty string]
import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { TextInput, Text, Button } from '@mantine/core';
export function Demo() {
const [value, setValue] = useState('');
const [debounced, cancel] = useDebouncedValue(value, 1000);
return (
<>
<TextInput
label="Enter value to see debounce"
value={value}
style={{ flex: 1 }}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<Button onClick={cancel} size="lg" style={{ marginLeft: 15 }}>
Cancel
</Button>
<Text>Value: {value}</Text>
<Text>Debounced value: {debounced}</Text>
</>
);
}

Definition

function useDebouncedValue<T = any>(
value: T,
wait: number,
options?: {
leading: boolean;
}
): readonly [T, () => void];
Build fully functional accessible web applications with ease
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback