A search component shows results for whatever the user types. Each keystroke triggers a lookup and displays "Results for: [query]". The result is always one step behind — it shows what was typed before the current keystroke, not the current value.
Type "a" — result shows "Results for: " (empty). Type "b" — result shows "Results for: a". Every result lags one keystroke behind. The display never catches up to what is currently in the input.
The setTimeout callback closes over query at the time it is created. By the time the callback runs, React has scheduled the state update but query still holds the value from before this render. The local variable val captures the value you actually want.
The setTimeout callback closes over query at the time it is created. By the time the callback runs, React has scheduled the state update but query still holds the value from before this render. The local variable val captures the value you actually want.