FrontEnd
React Query에는 Debounce와 Throttling이 없다?
DevInvestor
2022. 6. 13. 08:17
반응형
React-query에서 기본적으로 제공하는 debounce, throttling 기능이 없어 곤혹을 겪었다.
복습 및 예방 차원에서 구현을 학습해보자.
원리는 쿼리키 배열로 전달되는 값의 변화를 지연하여 전달하는 것이다.
참고한 글 : https://www.codingdeft.com/posts/react-debounce-throttle/
Debounce(디바운스)
- 일정 시간동안의 요청을 묶어 최종 요청 하나만 처리한다.
- 요청은 뒤에 트리거된다.
import React from "react";
export default function useDebounceValue<T>(value: T, delay: number = 500) {
const [debouncedValue, setDebouncedValue] = React.useState<T>(value);
React.useEffect(() => {
const handler: NodeJS.Timeout = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
Throttling(쓰로틀링)
- 일정 시간동안 추가 요청을 무시한다
- 요청은 앞에 트리거된다.
import React from "react";
export default function useThrottleValue<T>(value: T, delay: number = 500) {
const [throttleValue, setThrottleValue] = React.useState<T>(value);
const throttling = React.useRef(false);
React.useEffect(() => {
if (throttling.current === false) {
setThrottleValue(value);
throttling.current = true;
setTimeout(() => {
if (throttling?.current) throttling.current = false;
}, delay);
}
}, [value, delay]);
return throttleValue;
}
사용 방법
파라미터를 위의 훅으로 감싸 전달한다.
const debouncedSearchQuery = useDebounceValue(searchQuery, delay);
const { status, data, error, isFetching, isLoading } = useReactQuery(
debouncedSearchQuery,
"0"
);
반응형