Blog>
Snippets

Debouncing Input for Query Parameter Updates

Implement debouncing to delay state updates (and therefore URL parameter updates) until a certain period of no input has elapsed.
import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
    // State and effect for debouncing
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        // Set debouncedValue to value (passed in) after the specified delay
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        // Cancel the timeout if value changes (also on component unmount)
        return () => {
            clearTimeout(handler);
        };
    }, [value, delay]);

    return debouncedValue;
}
This custom hook `useDebounce` takes a value and delay as inputs and returns a debounced version of the value. It updates the debounced value only after the specified delay has passed without any new value changes, using `setTimeout` inside a `useEffect` hook.
import { useSearchParams } from 'react-router-dom';

function SearchInput() {
    const [searchParams, setSearchParams] = useSearchParams();
    const [inputValue, setInputValue] = useState('');
    const debouncedSearchTerm = useDebounce(inputValue, 500); // Delay of 500ms

    useEffect(() => {
        if (debouncedSearchTerm) {
            setSearchParams({ query: debouncedSearchTerm });
        }
    }, [debouncedSearchTerm, setSearchParams]);

    return (
        <input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder='Search...'
        />
    );
}
This component `SearchInput` uses the `useDebounce` hook to update search query parameters. It listens for changes to the input value, debounces these changes, and updates the URL search parameters with the debounced value using React Router's `useSearchParams` hook.