Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

How do I debounce a search input without losing the latest result?

clock icon

asked 2 months ago

message icon

1

eye icon

473

My debounced search occasionally renders stale results — a slow earlier request lands after a faster later one and overwrites it. Debouncing alone clearly isn't enough. How do people handle this?

1 Answer

You need cancellation on top of the debounce. The timer stops extra requests; a cancelled flag stops stale responses.

1useEffect(() => {
2 let cancelled = false
3
4 const timer = setTimeout(async () => {
5 const data = await search(query)
6 if (!cancelled) setResults(data)
7 }, 300)
8
9 return () => {
10 cancelled = true
11 clearTimeout(timer)
12 }
13}, [query])
1useEffect(() => {
2 let cancelled = false
3
4 const timer = setTimeout(async () => {
5 const data = await search(query)
6 if (!cancelled) setResults(data)
7 }, 300)
8
9 return () => {
10 cancelled = true
11 clearTimeout(timer)
12 }
13}, [query])

The cleanup runs before the next effect, so any in-flight response from a previous query is discarded rather than applied. With fetch you can go further and pass an AbortController signal so the request is dropped on the wire.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions