Async State Handling
Async State Handling covers pending fulfilled rejected lifecycles, race conditions, AbortController, duplicate submissions, and RTK Query.
Course: React — State Management Lesson: 08
Learning objectives
Model asynchronous operations, handle pending/success/failure states, prevent race conditions, cancel obsolete requests, and coordinate mutations.
Why async state is different
A synchronous state update is usually immediate from the application's perspective. A network request can take time, fail, be cancelled, or return after a newer request. The UI must represent these possibilities.
A basic lifecycle:
idle -> pending -> fulfilled-> rejected
Explicit request state
const [request, setRequest] = useState({status: "idle",data: null,error: null});
Use a single status when the states are mutually exclusive. For more complex workflows, model separate operations or use a reducer.
Handle a request from an event
async function handleSave(payload) {setRequest({ status: "pending", data: null, error: null });try {const result = await saveSettings(payload);setRequest({ status: "fulfilled", data: result, error: null });} catch (error) {setRequest({ status: "rejected", data: null, error });}}
A user-triggered mutation generally belongs in its event handler or mutation layer, not in an Effect triggered by a temporary flag.
Race conditions
Imagine a search request for rea starts first, then a request for react starts second. If the first response arrives last, it can overwrite the newer results. Cancel obsolete requests or ensure only the latest request is allowed to update the UI.
useEffect(() => {const controller = new AbortController();async function search() {try {const result = await searchProducts(query, {signal: controller.signal});setResults(result);} catch (error) {if (error.name !== "AbortError") setError(error);}}search();return () => controller.abort();}, [query]);
Async state in Redux Toolkit
createAsyncThunk can represent pending, fulfilled, and rejected lifecycle actions. A slice can respond to those actions in extraReducers. For endpoint caching and invalidation, RTK Query may be a better fit.
Mutations and duplicate submission
Disable or otherwise guard a submit action while a mutation is pending. For operations such as payment or order creation, also rely on backend validation and idempotency mechanisms where supported.
Common mistakes
- Treating pending as the only loading state.
- Ignoring rejected requests.
- Allowing older responses to overwrite newer results.
- Triggering a user mutation indirectly through an Effect.
- Retrying a mutation without considering duplicate side effects.
Best practices
Model request lifecycle explicitly, cancel or ignore obsolete requests, keep mutation handling close to the user event, and use server-state tooling when caching and synchronization become substantial.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What are pending, fulfilled, and rejected states?
BeginnerModel answer
They model an async lifecycle: request in flight, success with data, and failure with an error.
2How do you prevent duplicate submissions?
BeginnerModel answer
Track a pending mutation flag, disable the submit control, and ignore extra clicks until the request settles.
Intermediate
3What is a race condition in API-driven UI?
IntermediateModel answer
An older response arrives after a newer request and overwrites UI with stale results.
4When would you use RTK Query instead of createAsyncThunk?
IntermediateModel answer
When you need caching, invalidation, and endpoint-oriented server-state management rather than one-off thunks.
Advanced
5How can AbortController help?
AdvancedModel answer
It cancels an in-flight fetch during cleanup so obsolete requests stop and are not treated as normal failures.
Practice
Build a debounced search screen and a create-order form. Test slow responses, request failure, cancellation, and repeated submit clicks.