March 29, 2025

ikayaniaamirshahzad@gmail.com

πŸš€ Debouncing in JavaScript & React β€” Make Your App Smoother!


πŸ‘‹ Hey folks! I’m Rajat Sharma, and today we’re diving into an underrated but powerful concept: Debouncing.

Have you ever typed in a search bar and noticed how some apps wait a moment before responding?

That’s not lag β€” it’s debouncing, and it’s intentional.

In this article, you’ll learn:

  • What debouncing is
  • Why it matters in modern web apps
  • How to implement it in React (with real API examples!)
  • And the trade-off it brings

Let’s go! 🧠✨




🧩 What is Debouncing?

Debouncing is a technique used to delay the execution of a function until a certain time has passed since it was last called.

This is super useful for:

  • Typing in input fields
  • Window resizing
  • Rapid clicking

Without debouncing, each keystroke can fire an API call. That’s a lot of unnecessary traffic! 😱




πŸ§ͺ Real-Life Use Case

You’re building a postal code search.

User types 800001 β€” should we fire six API calls? NO!

Instead, wait a little after the last keystroke β†’ only fire one request. βœ…




🧰 Basic Setup (Without Debounce)

import axios from "axios";
import React from "react";

export default function App() {
  const setInput = (value) => {
    axios.get(`https://api.postalpincode.in/pincode/${value}`)
      .then((res) => {
        console.log(res.data[0]?.PostOffice[0]);
      });
  };

  return (
    <div>
      <input
        placeholder="Enter Pincode..."
        onChange={(e) => setInput(e.target.value)}
      />
    div>
  );
}
Enter fullscreen mode

Exit fullscreen mode

❌ Problem: Every keypress hits the API. Not efficient.




βœ… Debouncing with setTimeout + useEffect

Let’s optimize it!



1️⃣ Add state

const [pinCode, setPinCode] = React.useState("");
Enter fullscreen mode

Exit fullscreen mode



2️⃣ Update input on change

<input
  placeholder="Enter Pincode..."
  onChange={(e) => setPinCode(e.target.value)}
/>
Enter fullscreen mode

Exit fullscreen mode



3️⃣ Debounce API call in useEffect

React.useEffect(() => {
  const timer = setTimeout(() => {
    if (pinCode) {
      axios.get(`https://api.postalpincode.in/pincode/${pinCode}`)
        .then((res) => {
          console.log(res.data[0]);
        });
    }
  }, 2000); // 2 second debounce

  return () => clearTimeout(timer);
}, [pinCode]);
Enter fullscreen mode

Exit fullscreen mode

βœ… Now the API call triggers only after user stops typing for 2 seconds.




🧩 Full Working Code

import axios from "axios";
import React from "react";

export default function App() {
  const [pinCode, setPinCode] = React.useState("");

  React.useEffect(() => {
    const timer = setTimeout(() => {
      if (pinCode) {
        axios
          .get(`https://api.postalpincode.in/pincode/${pinCode}`)
          .then((res) => {
            console.log(res.data[0]);
          });
      }
    }, 2000);

    return () => clearTimeout(timer);
  }, [pinCode]);

  return (
    <div>
      <input
        placeholder="Enter Pincode..."
        onChange={(e) => setPinCode(e.target.value)}
      />
    div>
  );
}
Enter fullscreen mode

Exit fullscreen mode

πŸŽ‰ Now typing 800001 triggers just one API call!




🎯 Where Else Can You Use Debouncing?

  • πŸ” Search Bars
  • πŸ“ Form Auto-save
  • πŸͺŸ Resize Listeners
  • πŸ–±οΈ Button Clicks



πŸ”§ Bonus: Use lodash.debounce for Cleaner Code

Install it:

npm install lodash.debounce
Enter fullscreen mode

Exit fullscreen mode

Use it:

import debounce from "lodash.debounce";

const debouncedFetch = debounce((value) => {
  axios.get(`https://api.postalpincode.in/pincode/${value}`).then(...);
}, 2000);
Enter fullscreen mode

Exit fullscreen mode

This makes your code reusable and cleaner!




βš–οΈ Is Debouncing Making Your App Feel Slow?

That’s a good observation! Here’s the deal:



βœ… Pros:

  • Prevents API spamming
  • Smooths out performance
  • Saves server resources



⚠️ Cons:

  • Adds a perceived delay to the response
  • Not ideal when users expect instant feedback

🧠 My Take:

If your use case involves:

  • Heavy API calls
  • User typing/searching
    β†’ Use shorter debounce delays (e.g., 300-500ms)

Use 2000ms only when response is non-urgent or API is expensive.




🧠 Final Thoughts

Debouncing is a must-know for every developer.

It helps create apps that are efficient, responsive, and smooth.

So next time your UI lags behind your API β€” debounce it, don’t spam it!




πŸ™Œ Stay Connected

If this helped you out, drop a πŸ’¬ or ❀️ below!

πŸ§‘β€πŸ’» Happy Coding!

Let me know β€” I’d love to help you make this article shine even more!




Source link

Leave a Comment