Fetch data from an API in a Redux app and dispatch actions to update state when the request succeeds or fails.
Dispatch a Redux action only when a condition is true by reading current state inside a thunk function.
Chain multiple async steps together in one thunk, such as logging in and then fetching user data in sequence.
Already included in Redux Toolkit, no separate install needed if you are using configureStore from Redux Toolkit.
Redux Thunk is a small add-on for Redux, the popular state-management library for JavaScript apps. Redux on its own only knows how to handle plain, synchronous updates: you tell the store about an event by dispatching an action object, and a reducer updates the state. That works fine for simple changes, but it leaves you stuck when you need to do something like wait for a network request to come back before updating the state, or only dispatch an action if some condition is true. Redux Thunk fills that gap. The middleware lets you write action creators that return a function instead of an action object. That inner function receives the store's dispatch and getState methods as arguments, so it can look at the current state, run async logic such as an AJAX call, and then dispatch one or more real actions when the work is done. A thunk, in general programming terms, is a function that wraps an expression to delay its evaluation, and that is exactly what is happening here: the work is described once and run later, when the middleware invokes it. You can also inject a custom argument (such as an API service) into every thunk, which is convenient for swapping in a mock during tests. You would reach for Redux Thunk when you need to handle side effects in a Redux app, like fetching data, conditional dispatching, or chaining a few async steps together. If you are already using Redux Toolkit, the recommended modern Redux setup, the thunk middleware is included automatically, otherwise you install the redux-thunk package and wire it up with applyMiddleware. The codebase is written in TypeScript and published to npm.
← reduxjs on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.