tezvyn:

Debouncing a Search TextInput with Hooks

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

debounce with hooks.

OUTLINE

keep input in state, in an effect set a timer that fires the search after a delay, clear the timer on each change so only the final pause triggers the call.

WHAT THIS TESTS Whether you can throttle input-driven side effects correctly and avoid both excessive calls and race conditions.

A GOOD ANSWER COVERS Hold the current text in state, updated by the TextInput onChangeText handler. Do not call the API there. Instead use a useEffect that depends on the query value: inside it start a setTimeout that performs the fetch after a delay such as 300 to 500 milliseconds, and return a cleanup function that calls clearTimeout. Each keystroke updates state, which re-runs the effect; React first runs the cleanup from the previous run, canceling the pending timer, then schedules a new one. Only when the user pauses long enough does a timer survive and fire a single request. To handle out-of-order responses, track the latest query or use an AbortController so a slow earlier response does not overwrite results for the current query. You can encapsulate this in a reusable useDebounce hook that returns a debounced value, then run the effect on that debounced value.

COMMON WRONG ANSWERS Calling the API directly in onChangeText, which sends a request per keystroke. Forgetting clearTimeout, so timers accumulate and all eventually fire. Ignoring stale responses, letting an old result clobber the newest. Debouncing the state update itself rather than the side effect, causing laggy input.

LIKELY FOLLOW-UPS The difference between debounce and throttle. How AbortController cancels an in-flight fetch. Why the cleanup function is what makes the cancellation work.

ONE CONCRETE EXAMPLE A useDebounce hook stores value, and an effect sets a 400 ms timer to update debouncedValue, clearing it on change. A second effect fetches when debouncedValue changes. Typing fast keeps clearing the timer; only after the user stops for 400 ms does one search request fire.

Read the original → usehooks.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.