Use useState for query, suggestions, highlight, isLoading, isOpen. Use useEffect for debounce (setTimeout in useEffect with query dependency) and click-outside listener. Use useRef for the container and debounce timer. Handle keyboard navigation in handleKeyDown.
How do you build an autocomplete in React?
More FAQs in Autocomplete Search Bar in React
Use useEffect with the query as a dependency. Set a setTimeout inside useEffect. Return () => clearTimeout(timer) as the cleanup. This creates a debounced effect that runs 300ms after the query changes.
Use useEffect to add a document click listener. Check if the click is inside the container using a ref: if (containerRef.current && !containerRef.current.contains(e.target)) setIsOpen(false). Remove the listener in the cleanup.
Add onKeyDown to the input. Use setHighlight with a functional update: ArrowDown -> setHighlight(h => Math.min(h + 1, suggestions.length - 1)). Enter -> onSelect(suggestions[highlight]). Escape -> setIsOpen(false).
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.