React Debouncing Explained with Real Search API Example (JavaScript)

React Debouncing Explained with Real Search API Example (JavaScript)

Debouncing is a powerful technique in JavaScript and React, especially when you are working with search inputs and live API calls. Without debouncing, your app may call the API on every key press, which makes the UI slow and wastes network calls.

🔥 In this post you’ll learn:
  • What debouncing is
  • Why it’s important in React
  • A real search API example using fetch()

🎥 Watch the Video Explanation

Prefer learning by watching? Here is the full YouTube video from Code With Sanyogita:

👉 You can also open it directly on YouTube: React Debouncing – Search API Example


What is Debouncing?

Debouncing means: “Wait for the user to stop typing, then run the function.”

Common use cases:

  • Search bars (API-based search)
  • Resize / scroll listeners
  • Buttons that should not trigger too often

Reusable Debounce Function (JavaScript)

let timer;



function debounce(fn, delay) {

  return function (...args) {

    clearTimeout(timer);

    timer = setTimeout(() => fn.apply(this, args), delay);

  };

}

Every time the user types, the previous timer is cleared and a new one is started. The function runs only when the user pauses for the given delay.

React Debounced Search Example

import { useState } from "react";



let timer;

function debounce(fn, delay) {

  return function (...args) {

    clearTimeout(timer);

    timer = setTimeout(() => fn.apply(this, args), delay);

  };

}



export default function DebounceSearch() {

  const [search, setSearch] = useState("");

  const [results, setResults] = useState([]);



  function callSearchAPI(query) {

    fetch(`https://dummyjson.com/products/search?q=${query}`)

      .then((res) => res.json())

      .then((data) => {

        setResults(data.products || []);

        console.log("API called with:", query);

      });

  }



  const debouncedAPI = debounce(callSearchAPI, 600);



  function handleChange(e) {

    const value = e.target.value;

    setSearch(value);



    if (value.trim() === "") {

      setResults([]);

      return;

    }



    debouncedAPI(value);

  }



  return (

    <div style={{ padding: "20px" }}>

      <input

        placeholder="Search product..."

        value={search}

        onChange={handleChange}

        style={{ padding: "10px", width: "250px" }}

      />



      {results.length > 0 && (

        <ul>

          {results.map((item) => (

            <li key={item.id}>{item.title}</li>

          ))}

        </ul>

      )}

    </div>

  );

}

How This Works Step-by-Step

  1. User types into the search input.
  2. handleChange updates state and calls debouncedAPI.
  3. Debounce clears the old timer and starts a new one.
  4. If user keeps typing, the timer resets and API is NOT called.
  5. When user pauses for 600ms, API is finally called once.

Benefits:

  • Fewer API calls
  • Faster and smoother UI
  • Better user experience

Where You Should Use Debouncing

  • Search inputs (like this example)
  • Live filters and typeahead suggestions
  • Scroll / resize events that fire many times per second

Debouncing is a small concept, but it makes a big difference in real-world React apps. Start using it in your search components and API calls to immediately improve performance.

More React and JavaScript tips are coming on Code With Sanyogita 🚀


👩‍💻 Written by Code With Sanyogita

Frontend Developer & content creator sharing beginner-friendly tutorials on React, JavaScript, and Web Development.

If this post helped you, consider subscribing on YouTube for more real-world coding examples 🚀

Comments

Popular posts from this blog

JavaScript Closure Explained with a Real React Example (Movie Ticket Booking)

React Keys: Index vs ID Explained (Delete Item Bug with Example)