Debouncing the Search

Learn about the search functionality from a traditional button-triggered search to a dynamic debounced search UI.

Implementing the search bar

We all have used Google to search for something at some point. When we type in the search bar, a drop-down slides down to provide the closest matches following the user input. It's a very smooth user experience, as Google has trained all of us to get used to it for decades, as shown in the image below:

Press + to interact
Debouncing the search UI
Debouncing the search UI

Debouncing the search UI

There's no search button the user can click anymore; all the user needs to do is to keep typing. And when the user stops typing, the matched list is revealed. So, how do we implement this? Let's first remove the "Search" button:

const Title = () => {
// State for managing input text and search query
const [text, setText] = useState('');
const [query, setQuery] = useState('');
// Memoized result of fruits filtered based on the search query
const matched = useMemo(() => {
console.log('created', query); // ➀
return fruits.filter(v => v.includes(query));
}, [query]);
// Event handler for updating the 'text' and 'query' states on input change
const onType = e => {
const inputValue = e.target.value;
setText(inputValue);
setQuery(inputValue);
}
console.log('updated', text); // ➁
return (
<>
<input value={text} onChange={onType} />
{matched.join(',')}
</>
);
}
memoized the fruits.filter result. Log is created at ➀ and updated at ➁, updating on text input

Although we don't have the button to click, the nature of this click-to-search doesn't change. Somehow, we still need a moment of this "click" when the user is about to finish typing and expect a search to happen. So, the idea here is to find the right "click" moment.

How exactly can we know such timing, when something is about to happen but has not happened yet? Actually, there's a perfect analogy for this problem. Ever wondered how an elevator waits for all people to get inside before it closes its door? How does the door know ...