Redux Thunk
Thunk middleware for Redux.
npm install --save redux-thunkNote on 2.x Update
Most tutorials today assume Redux Thunk 1.x so you might run into an issue when running their code with 2.x.
If you use Redux Thunk 2.x in CommonJS environment, don’t forget to add .default to your import:
- var ReduxThunk = require('redux-thunk')
+ var ReduxThunk = require('redux-thunk').defaultIf you used ES modules, you’re already all good:
import ReduxThunk from 'redux-thunk' // no changes here 😀Additionally, since 2.x, we also support a UMD build:
var ReduxThunk = window.ReduxThunk.defaultAs you can see, it also requires .default at the end.
Why Do I Need This?
If you’re not sure whether you need it, you probably don’t.
Read this for an in-depth introduction to thunks in Redux.
Motivation
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.
An action creator that returns a function to perform asynchronous dispatch:
An action creator that returns a function to perform conditional dispatch:
What’s a thunk?!
A thunk is a function that wraps an expression to delay its evaluation.
The term originated as a humorous past-tense version of "think".
Installation
Then, to enable Redux Thunk, use applyMiddleware():
Composition
Any return value from the inner function will be available as the return value of dispatch itself. This is convenient for orchestrating an asynchronous control flow with thunk action creators dispatching each other and returning Promises to wait for each other’s completion:
Injecting a Custom Argument
Since 2.1.0, Redux Thunk supports injecting a custom argument using the withExtraArgument function:
To pass multiple things, just wrap them in a single object and use destructuring:
License
MIT
Last updated
Was this helpful?