React · Middle · Question 13 of 75
How do you avoid a race when loading data in useEffect if userId changes quickly?
- ✓Correct answer: An
ignoreflag or anAbortControllerin cleanup - 2Add a 300 ms
setTimeoutbefore each request - 3Remove
userIdfrom the effect's dependency array
Explanation
Responses can arrive out of order, and an old response overwrites a new one. In cleanup, set ignore = true (the result is ignored) or call controller.abort() (the request is cancelled). Even better, use TanStack Query or framework data loading, where this is solved.