코드도보통지

5관문. Debounce & Throttle Hooks

관문 5 / 7

useDebounce(값 지연)와 useThrottle(함수 제어)의 차이를 구현으로 체득하라.

📖 이론 비급

Debounce vs Throttle

Debounce: 마지막 이벤트로부터 일정 시간 후 한 번 실행. 연속 타이핑이 끝난 후 검색 실행에 적합하다.

Throttle: 일정 시간 간격마다 최대 한 번 실행. 스크롤, 마우스 이동처럼 연속적인 이벤트 제어에 적합하다.

두 패턴 모두 타이머 ID를 ref에 저장하고 cleanup에서 정리해야 한다.

⚔️ 수련 코드

import { useState, useEffect, useRef, useCallback } from 'react';

// TODO: useDebounce 구현 (값을 delay ms 후에 반영)
function useDebounce(value, delay) {
}

// TODO: useThrottle 구현 (함수를 delay ms 간격으로 제한)
function useThrottle(fn, delay) {
}

export default function EventDemo() {
  const [input, setInput] = useState('');
  const [scroll, setScroll] = useState(0);

  const debouncedInput = useDebounce(input, 500);
  const throttledScroll = useThrottle((y) => setScroll(y), 200);

  useEffect(() => {
    const handler = (e) => throttledScroll(window.scrollY);
    window.addEventListener('scroll', handler);
    return () => window.removeEventListener('scroll', handler);
  }, [throttledScroll]);

  return (
    <div style={{ height: 2000 }}>
      <div style={{ position: 'fixed', top: 0, background: '#fff', padding: 8 }}>
        <input value={input} onChange={e => setInput(e.target.value)} placeholder="타이핑..." />
        <p>디바운스: {debouncedInput}</p>
        <p>스크롤 (쓰로틀): {scroll}px</p>
      </div>
    </div>
  );
}