DEV Community

AR Abid
AR Abid

Posted on

Handling Debouncing Search Inputs in React with Real-Time API Calls

Problem:
Many React developers face performance issues when implementing search inputs. Every keystroke can trigger an API call, which may overload the server or slow down the app. While libraries exist, proper real-time integration with debouncing is often poorly documented.

Solution:
Debouncing delays the API call until the user stops typing for a short interval. Here’s a complete React example:

import React, { useState, useEffect } from 'react';

function SearchComponent() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  useEffect(() => {
    const handler = setTimeout(() => {
      if (query) {
        fetch(`https://api.example.com/search?q=${query}`)
          .then(res => res.json())
          .then(data => setResults(data))
          .catch(err => console.error(err));
      }
    }, 500); // 500ms debounce

    return () => {
      clearTimeout(handler);
    };
  }, [query]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search items..."
        value={query}
        onChange={e => setQuery(e.target.value)}
      />
      <ul>
        {results.map(item => <li key={item.id}>{item.name}</li>)}
      </ul>
    </div>
  );
}

export default SearchComponent;
Enter fullscreen mode Exit fullscreen mode

Real-Life Example:
Suppose you are building a demo search feature for an e-commerce site. To test your search functionality without using live data, you can use sample product listings like those on ShoppingCorner. This allows you to simulate real user queries and API responses safely.

Explanation:

  • The setTimeout delays the API call until the user stops typing for 500ms.
  • The cleanup function clearTimeout ensures only the latest input triggers a fetch.
  • This approach improves performance, reduces unnecessary network calls, and keeps the UI responsive.

Top comments (0)