use-debounced-value
use-debounced-value
값을 디바운스하는 use-debounced-value 훅에 대해 설명해 드릴게요. @mantine/hooks 패키지에서 제공돼요.
출처: 문서
본문
사용법
import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { TextInput, Text } from '@mantine/core';
function Demo() {
const [value, setValue] = useState('');
const [debounced] = useDebouncedValue(value, 200);
return (
<>
<TextInput
label="Enter value to see debounce"
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<Text>Value: {value}</Text>
<Text>Debounced value: {debounced}</Text>
</>
);
}
use-debounced-state와의 차이점
- 디바운스되지 않은 값에 직접 접근할 수 있어요.
- 제어 입력(
defaultValue대신valueprop)에 사용돼요. 예를 들어 입력에 입력된 문자처럼 매 state 변경마다 렌더링돼요. - props나 다른 state 공급자와 함께 동작하고,
useState사용을 강제하지 않아요.
Leading 갱신
{ leading: true } 옵션으로 첫 호출에서 값을 즉시 갱신할 수 있어요:
import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { TextInput, Text } from '@mantine/core';
function Demo() {
const [value, setValue] = useState('');
const [debounced] = useDebouncedValue(value, 200, { leading: true });
return (
<>
<TextInput
label="Enter value to see debounce"
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<Text>Value: {value}</Text>
<Text>Debounced value: {debounced}</Text>
</>
);
}
Cancel과 flush
훅은 cancel과 flush 핸들러가 있는 세 번째 요소를 반환해요. cancel은 대기 중인 갱신을 버리고, flush는 즉시 적용해요. 갱신은 컴포넌트 언마운트 시 자동으로 취소돼요.
이 예시에서 텍스트를 입력하고 1초 안에 cancel 버튼을 클릭하면 디바운스 값 변경을 취소할 수 있어요:
import { useState } from 'react';
import { useDebouncedValue } from '@mantine/hooks';
import { TextInput, Text, Button } from '@mantine/core';
function Demo() {
const [value, setValue] = useState('');
const [debounced, cancel] = useDebouncedValue(value, 1000);
return (
<>
<TextInput
label="Enter value to see debounce"
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<Button onClick={cancel} size="lg">
Cancel
</Button>
<Text>Value: {value}</Text>
<Text>Debounced value: {debounced}</Text>
</>
);
}
반환 튜플의 두 번째 요소는 이전 버전과의 호환성을 위한 cancel의 약칭이에요:
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>
내보내는 타입
UseDebouncedValueOptions와 UseDebouncedValueReturnValue 타입은 @mantine/hooks 패키지에서 내보내지므로 애플리케이션에서 import할 수 있어요:
import type { UseDebouncedValueOptions, UseDebouncedValueReturnValue } from '@mantine/hooks';
더 알아보기 (Learn more)
- use-debounced-state — use-debounced-state 훅
- use-disclosure — use-disclosure 훅