연달아 발생하는 이벤트 중 처음 혹은 마지막 이벤트만 실행
예시 : 연관검색어
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(
() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
},
[value, delay]
);
return debouncedValue;
}
이벤트 발생 후 일정 시간이 흐른 후 이벤트 실행
예시 : 무한스크롤
import { useRef } from 'react';
function useThrottle<T extends any[]>(callback: (...params: T) => void, time: number) {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
return (...params: T) => {
if (!timer.current) {
timer.current = setTimeout(() => {
callback(...params);
timer.current = null;
}, time);
}
};
}
export default useThrottle;
라이브러리 Lodash 로 구현 가능