DEV Community

Discussion on: Debouncing with React Hooks

Collapse
 
georgewl profile image
George WL

whilst I like the idea of this, I think the UI and the API call should be far more decoupled, so instead I've went for:

// in the useDebounce file
import { useEffect } from 'react';
/**
 * @description for use in functions with side-effects but no return value
 * @export useDebouncedFunction
 */
export default function useDebouncedFunction(handler, watchedValue, delay) {
  useEffect(() => {
    const timeoutHandler = setTimeout(() => {
      handler();
    }, delay);
    return () => {
      clearTimeout(timeoutHandler);
    };
  }, [watchedValue, delay]);
}

// in the search file
  const [searchQuery, setSearchQuery] = React.useState('');

  const fetchX = async () => {
    await getX()
      .then((updatedStock: IStockResponse) => {
        setX(updated.data?? []);
      })
      .catch(err => {
        console.error(err);
      });
  };
  useDebouncedFunction(fetchStockVehicles, searchQuery, 1000);
  const handleSearch = (value: string) => {
    setSearchQuery(value ?? '');
  };

Enter fullscreen mode Exit fullscreen mode