Here's a custom useDebounceSearch hook that debounces the search input and returns the debounced value along with loading state:
import { useEffect, useState } from "react";
export function useDebounceSearch(value: string, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
const [isDebouncing, setIsDebouncing] = useState(false);
useEffect(() => {
setIsDebouncing(true);
const timer = setTimeout(() => {
setDebouncedValue(value);
setIsDebouncing(false);
}, delay);
return () => clearTimeout(timer);
}, [value, delay]);
return { debouncedValue, isDebouncing };
}Here's an example search component using the hook:
import { useState } from "react";
import { useDebounceSearch } from "./use-debounce-search";
export function SearchInput() {
const [query, setQuery] = useState("");
const { debouncedValue, isDebouncing } = useDebounceSearch(query);
useEffect(() => {
if (!debouncedValue) return;
fetch("/api/search?q=" + debouncedValue)
.then((res) => res.json())
.then(setResults);
}, [debouncedValue]);
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
{isDebouncing && <span>Searching...</span>}
</div>
);
}Developer-focused chat interface with syntax-highlighted code blocks, language badges, copy-to-clipboard buttons, and file name tabs. Optimized for code generation and programming assistance.