DevPath
Mid lesson · 12 min

Design a resilient search flow

Combine debounce, cancellation and explicit result states.

Reduce unnecessary work

Debounce waits for a brief pause before starting a search. It reduces calls while someone types, but it does not stop an already-started request. Cancel or ignore obsolete work when the query changes. Also handle a cleared query without sending an unnecessary request.

Represent the result precisely

A search can be idle, loading, successful with items, successful with no items, or failed. A discriminated union makes each state explicit and helps TypeScript flag missing branches. The view should distinguish 'no matches' from 'could not search'.

type SearchState =
  | { kind: 'idle' }
  | { kind: 'loading'; query: string }
  | { kind: 'ready'; query: string; items: Item[] }
  | { kind: 'error'; query: string; message: string };

Keep the query aligned

Store the query that produced each result. If the input changes while a request is in flight, do not label old results as new ones. Test rapid typing, clearing the field, one failed response, and a slow old response arriving last. Make the loading announcement accessible without speaking every keystroke.

Check your understanding

Does debounce alone prevent stale search results?

Show explanation

No. It delays starting requests, but an older in-flight request can still finish later. Cancel or ignore stale responses.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Cancel outdated search requests

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.