State Management
React Redux Async Thunks
createAsyncThunk wraps an async function and dispatches pending, fulfilled and rejected actions automatically, so a slice can handle loading and error state without extra action creators.
What is Redux Async Thunks in React?
createAsyncThunk wraps an async function and dispatches pending, fulfilled and rejected actions automatically, so a slice can handle loading and error state without extra action creators.
Redux Async Thunks example
JavaScript
export const fetchJobs = createAsyncThunk('jobs/fetch', async (city) => {
const res = await fetch(`/api/jobs?city=${city}`);
if (!res.ok) throw new Error('Failed to load jobs');
return res.json();
});
const jobsSlice = createSlice({
name: 'jobs',
initialState: { items: [], status: 'idle', error: null },
reducers: {},
extraReducers: builder => {
builder
.addCase(fetchJobs.pending, s => { s.status = 'loading'; })
.addCase(fetchJobs.fulfilled, (s, a) => { s.status = 'success'; s.items = a.payload; })
.addCase(fetchJobs.rejected, (s, a) => { s.status = 'error'; s.error = a.error.message; });
},
});Key points to remember
- Dispatch it like any action: dispatch(fetchJobs("Pune")).
- The returned promise has an unwrap() method if you need to await the result in a component.
- RTK Query replaces thunks entirely for plain data fetching.
Common mistakes with Redux Async Thunks
- Putting server data in Redux when a query library would cache and revalidate it for you.
- Forgetting the rejected case, so failures leave the UI stuck loading.
React Redux Async Thunks— Interview Questions & FAQs
Thunks or RTK Query?+
RTK Query for straightforward fetching and caching — it removes the loading and error boilerplate entirely. Thunks when the async logic coordinates several slices or has genuinely custom flow.
