Redux & Redux Toolkit
/Intermediate
Redux Thunk
Definition
A middleware that allows you to write action creators that return a FUNCTION instead of an action object. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.
Explain Like I'm New
A Thunk is just a function that wraps around another function to delay its execution. In Redux, when you dispatch a Thunk (a function), the Thunk middleware intercepts it, stops it from hitting the reducer, runs your API call, and then manually `dispatch()`es the final data when it's ready.
Real World Example
You dispatch `loginUser(credentials)`. The Thunk intercepts it, sends the credentials to the backend, gets a Token, and then dispatches `{ type: 'LOGIN_SUCCESS', payload: Token }` to the reducer.
Common Use Cases
- •API integrations
- •Complex synchronous logic that needs access to `getState`
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- Does RTK's `configureStore` require you to install Redux Thunk manually?
intermediate
- What two arguments does a Thunk function receive when the middleware executes it?