[React] Debounce vs Throttle

민병대·2023년 4월 11일
0

Debounce

연달아 발생하는 이벤트 중 처음 혹은 마지막 이벤트만 실행
예시 : 연관검색어

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(
    () => {
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);
      return () => {
        clearTimeout(handler);
      };
    },
    [value, delay]
  );
  return debouncedValue;
}

Throttle

이벤트 발생 후 일정 시간이 흐른 후 이벤트 실행
예시 : 무한스크롤

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 로 구현 가능

profile
마케터 출신 개발자

0개의 댓글