React by Patrik

Debouncing in the SearchInput Component

Overview: Debouncing is a technique that limits the rate at which a function is invoked, especially in cases like search input, where every keystroke could trigger an expensive operation such as an API call or a state update. In this solution, debouncing is applied to the search input field, ensuring that the search query is only processed after the user has stopped typing for a specified period, thus reducing unnecessary re-renders.

Implementation: The SearchInput component is responsible for capturing user input. However, instead of immediately sending the input to the parent component or making API calls, we use a debouncing hook (useDebouncedValue) to delay updates until the user stops typing for a set period (e.g., 800ms).

import React, { useState, useEffect, useCallback } from "react";
import { useDebouncedValue } from "../../services/hooks/useDebouncedValue";

function SearchInput({ initialQuery, onDebouncedQueryChange }) {
  const [searchQuery, setSearchQuery] = useState(initialQuery || "");
  const debouncedQuery = useDebouncedValue(searchQuery, 800);

  useEffect(() => {
    onDebouncedQueryChange(debouncedQuery);
  }, [debouncedQuery, onDebouncedQueryChange]);

  const handleInputChange = useCallback((e) => {
    setSearchQuery(e.target.value);
  }, []);

  return (
    <input
      type="text"
      value={searchQuery}
      onChange={handleInputChange}
      placeholder="Search..."
    />
  );
}

This implementation ensures that the parent component (SearchPage) receives the debounced query and only passes it to the child SearchList when the user has stopped typing for a period, optimizing performance.

Comments