사툰사툰

useDebounce

특정 값에 디바운스를 적용하는 훅입니다

97

useDebounce.ts
import { useEffect, useState } from 'react';

/**
 * debounce hook
 * @param value
 * @param delay
 * @returns
 */
export default function useDebounce<T>(value: T, delay = 200): T {
  const [debounceValue, setDebounceValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebounceValue(value);
    }, delay);
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debounceValue;
};