Thunks and Redux Toolkit
Get started with thunks and Redux toolkit.
We'll cover the following...
Introduction
Do you remember what “thunks” are? Here’s a quick reminder.
When you first learn Redux, you were likely taught that you must dispatch an action to make a state change and that the action has to be an object. Usually, it is in the following form:
{
type: "ACTION_TYPE",
payload: {}
}
Well, that’s not entirely true.
In the typical flow of a Redux app, the reducer is the only actor that requires the action to be an object!
This means you can dispatch whatever Javascript data type you want but must transform it into an object before it reaches the reducers.
This is the entire premise on which thunks are built.
By dispatching a “function” (aka thunk), a middleware could act on it. It could even pass it special arguments.
So, what is a “thunk”?
Generally speaking, a thunk is a function that wraps an expression to delay its evaluation.
If you choose to return a function from an action creator, we can safely call that a thunk.
// before:
function
...