Handle race conditions in useEffect by using cleanup functions to set a flag (isMounted), using AbortController to cancel in-flight requests, or simply switching to data fetching libraries like SWR or React Query that handle this automatically
Race conditions in client-side data fetching occur when a component fetches data multiple times in rapid succession, and responses arrive out of order—an older request completes after a newer one, overwriting the latest data with stale information. This is particularly common in scenarios like search inputs, tab switching, or route changes. In useEffect, race conditions happen because there's no built-in mechanism to cancel pending requests when dependencies change. You must manually handle cleanup to ensure that only the most recent request updates the component state.
Another approach is using useRef to track the current request and ignore outdated responses. This is useful when you can't cancel requests (e.g., with some third-party APIs) but need to ensure only the latest response updates state. The pattern involves incrementing a request counter and checking it in the response handler .
The most robust solution is to avoid manual useEffect data fetching entirely and use libraries like SWR or React Query. These libraries handle request deduplication, caching, and race condition prevention out of the box. SWR automatically cancels stale requests when new ones are made, and React Query's query keys ensure that only the latest data for a given key is stored .
Mounted flag (isMounted): Simplest solution for preventing updates after unmount, but doesn't stop the request itself from completing and wasting resources .
AbortController: Best for modern browsers—actually cancels network requests, saving bandwidth and processing. Works with fetch and can be polyfilled .
Request ID tracking: Useful when working with APIs that don't support cancellation (e.g., legacy XMLHttpRequest or certain SDKs) .
SWR/React Query: The recommended approach for production applications—handles race conditions, caching, and many other edge cases automatically .