- Thunks in Redux: The BasicsWhat Thunks Are, What They Solve, Other OptionsThis article was born as a gist for React Redux beginners, intended to demystify what thunks are and the motivation for using them.Redux was created by Dan Abramov for a talk.
- It provides a predictable approach to managing state that benefits from immutability, keeps business logic contained, acts as the single source of truth, and has a very small API.The synchronous and pure flow of data through Redux’s components is well-defined with distinct, simple roles.
- Notice how a thunk (the function returned from thunkedYell(…)) requires an extra invocation before the work is executed:Here the potential work involves a side effect (logging), but thunks can also wrap calculations that might be slow, or even unending.
- In any case, other code can subsequently decide whether to actually run the thunk:Aside: LazinessLazy languages like Haskell treat function arguments as thunks automatically, allowing for “infinite” computed-on-demand lists and clever compiler optimizations.
- Thunks in React ReduxIn React / Redux, thunks enable us to avoid directly causing side effects in our actions, action creators, or components.
For React & Redux beginners, intended to demystify thunks and the motivation for using them.
This article was born as a gist for React & Redux beginners, intended to demystify what thunks are and the motivation for using them.
Redux was created by Dan Abramov for a talk. It is a “state container” inspired by the unidirectional Flux data flow and functional Elm architecture. It provides a predictable approach to managing state that benefits from immutability, keeps business logic contained, acts as the single source of truth, and has a very small API.
The synchronous and pure flow of data through Redux’s components is well-defined with distinct, simple roles. Action creators create objects → objects are dispatched to the store → the store invokes reducers → reducers generate new state → listeners are notified of state updates.
However, Redux is not an application framework, and does not dictate how effects should be handled. For that, developers can adopt any preferred strategy through middleware.
I’d probably let action creator return a function. If it’s a function, it’s given dispatch and the state. — Dan Abramov , responding to issue #1 in Redux.
Redux-Thunk is arguably the most primitive such middleware. It is certainly the first that most people learn, having been written by Dan Abramov as part of Redux proper before being split out into a separate package. That original implementation is tiny enough to quote in its entirety:
Since then, the Redux-Thunk source code has only expanded to fourteen lines total. Despite this apparent simplicity,…