Thunk is a middleware for Redux.
To understand this, let’s see what Redux is in the first place. Redux is a JavaScript library for managing application state. It has a few key concepts like:
We won’t dive into the details, but just know that actions contain information that is dispatched to reducers. The middleware sits between the dispatch and reducers.
The Redux middleware provides a third-party extension point between dispatching an action and the moment it reaches the reducer.
Thunk is one such middleware that allows you to write action creators that return a function instead of an action. This interception of actions before reaching the reducers enables you to incorporate logic like, “delay the dispatch of action” or “only dispatch if a certain condition is met.”
npm install redux-thunk
Below, an action creator returns a function to perform conditional dispatch.
The function printWelcomeIfNewUser()
wraps the function printWelcome()
and adds logic, dispatch printWelcome()
, but only if the isNewUser
state is true.
function printWelcomeIfNewUser() {return (dispatch, getState) => {const { isNewUser } = getState();if (!isNewUser) {return;}dispatch(printWelcome());};}
Free Resources