DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

React Debounce - Search -Query


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

const SearchBounce = (props) => {
  const [query, setQuery] = useState("");

  const printData = useCallback((data) => {
    console.log("data", data);
    // You can perform your search or other operations here using the 'data'
  }, []);

  useEffect(() => {
    const timer = setTimeout(() => {
      printData(query);
    }, 1000); // Adjust the debounce delay as needed

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

  const handleInputChange = (event) => {
    setQuery(event.target.value);
  };

  return (
    <div>
      <h2>Debounce Example List</h2>
      <input
        type="text"
        value={query}
        onChange={handleInputChange}
        placeholder="Search..."
      />
    </div>
  );
};

export default SearchBounce;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)