Trusted answers to developer questions

What is Redux Thunk?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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:

  • ‘actions’
  • ‘action creators’
  • ‘reducers’
  • ‘dispatch’
  • ‘middleware’
svg viewer

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.”

Installation

npm install redux-thunk

Example

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());
};
}

RELATED TAGS

thunk
redux
react
web development
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?