gitmyhub

redux-thunk

TypeScript ★ 18k updated 1y ago

Thunk middleware for Redux

A tiny Redux add-on that lets you write async logic like API calls as functions instead of plain action objects, so you can fetch data and dispatch updates to the store when the work finishes.

TypeScriptJavaScriptReduxsetup: easycomplexity 2/5

Redux Thunk is a small add-on for Redux, the popular state-management library for JavaScript apps. Redux on its own only knows how to handle plain, synchronous updates: you tell the store about an event by dispatching an action object, and a reducer updates the state. That works fine for simple changes, but it leaves you stuck when you need to do something like wait for a network request to come back before updating the state, or only dispatch an action if some condition is true. Redux Thunk fills that gap.

The middleware lets you write action creators that return a function instead of an action object. That inner function receives the store's dispatch and getState methods as arguments, so it can look at the current state, run async logic such as an AJAX call, and then dispatch one or more real actions when the work is done. A thunk, in general programming terms, is a function that wraps an expression to delay its evaluation, and that is exactly what is happening here: the work is described once and run later, when the middleware invokes it. You can also inject a custom argument (such as an API service) into every thunk, which is convenient for swapping in a mock during tests.

You would reach for Redux Thunk when you need to handle side effects in a Redux app, like fetching data, conditional dispatching, or chaining a few async steps together. If you are already using Redux Toolkit, the recommended modern Redux setup, the thunk middleware is included automatically; otherwise you install the redux-thunk package and wire it up with applyMiddleware. The codebase is written in TypeScript and published to npm.

Where it fits