Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

thunk
redux
react
web development

What is Redux Thunk?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring