DEV Community

Cover image for React: Debouncing input with useEffect
Reme Le Hane
Reme Le Hane

Posted on • Originally published at remejuan.substack.com

2

React: Debouncing input with useEffect

Debouncing is a technique that ensures a function is only called after a certain period of time has passed since the last event. It’s often used in cases like search inputs, where you don’t want to make an API call on every keystroke but only after the user has finished typing.

Example: Debouncing a Search Input

Let’s say you have a search input that makes an API call. Without debouncing, it would make an API call for every keystroke, which is inefficient. Here’s how you can debounce it using useEffect:

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

const DebouncedSearch = () => {
  const [query, setQuery] = useState("");  // The search query typed by user
  const [debouncedQuery, setDebouncedQuery] = useState(query);  // Debounced value

  useEffect(() => {
    // Set a timeout to update debounced value after 500ms
    const handler = setTimeout(() => {
      setDebouncedQuery(query);
    }, 500);

    // Cleanup the timeout if `query` changes before 500ms
    return () => {
      clearTimeout(handler);
    };
  }, [query]);

  // Whenever debouncedQuery changes, simulate an API call
  useEffect(() => {
    if (debouncedQuery) {
      console.log("API call with query:", debouncedQuery);
      // Make API call here
    }
  }, [debouncedQuery]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <p>Debounced Query: {debouncedQuery}</p>
    </div>
  );
};

export default DebouncedSearch;
Enter fullscreen mode Exit fullscreen mode

How it works:

  1. State: query stores the immediate input value, and debouncedQuery stores the value after the debounce period.
  2. useEffect (Debounce): When query changes, a timeout is set for 500ms. If the user stops typing, the debouncedQuery is updated after 500ms. If the user types again before 500ms, the timeout is cleared, and a new one is set.
  3. useEffect (API call): Once the debouncedQuery is updated, we can simulate the API call.

This way, you only trigger the API call when the user finishes typing, improving performance and avoiding unnecessary requests.

Key takeaway: Using debouncing in input-heavy components keeps them efficient and responsive without making too many API calls or expensive operations.

💡 One last tip before you go

Spend Less on Your Side Projects

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

Check out DEV++

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay