Code Generation Chat with Syntax Highlighting

Create a React hook for debounced search with TypeScript.
JD
AI

Here's a custom useDebounceSearch hook that debounces the search input and returns the debounced value along with loading state:

use-debounce-search.tstypescript
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 };
}
Can you show me how to use it in a component?
JD
AI

Here's an example search component using the hook:

search-input.tsxtsx
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>
  );
}
About this block

Code Generation Chat with Syntax HighlightingPRO

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.

More Chat blocks

View all Chat
PRO

chat12

Conversational Thread with Reactions

PRO

chat11

Complete AI Chat Interface

PRO

chat16

Multi-Agent Chat with Personas

Get Pro access