MuTasim

useDebounce.

As a developer, I often encounter scenarios where I need to optimize performance in my React applications, especially when dealing with frequent user input. That's where my trusty custom hook, useDebounce, comes into play.

./hooks/useDebounce.tsx
import { useState, useEffect } from 'react';

function useDebounce<T>(value: T, delay?: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay || 500);

    return () => {
      clearTimeout(timer);
    }

  }, [value, delay])

  return debouncedValue;
}

Whether I'm implementing a live search feature or handling user-input-driven API requests, useDebounce has become my go-to solution. It ensures that my applications remain snappy and responsive, providing users with a seamless experience.