Why use redux-thunk?

micahblu picture micahblu · May 4, 2017 · Viewed 13.1k times · Source

I don't understand the need for something like redux-thunk. From what I understand a thunk is a function which returns a function. The wrapped expressions and the use of middleware appear to me to do more to obfuscate what is happening. Taken from redux-thunk's sample code

import thunk from 'redux-thunk';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);


// Meet thunks.
// A thunk is a function t hat returns a function.
// This is a thunk.

function makeASandwichWithSecretSauce(forPerson) {

  // Invert control!
  // Return a function that accepts `dispatch` so we can dispatch later.
  // Thunk middleware knows how to turn thunk async actions into actions.

  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}

// Thunk middleware lets me dispatch thunk async actions
// as if they were actions!

store.dispatch(
  makeASandwichWithSecretSauce('Me')
);

The above code could be written far more concisely and intuitive:

fetchSecretSauce().then(
  sauce => store.dispatch(makeASandwich('Me', sauce)),
  error => store.dispatch(apologize('The Sandwich Shop', forPerson, error))
)

My question is what need is redux-thunk fulfilling and how does it improve on existing solutions similar to the example above.

Answer

Mo Ismat picture Mo Ismat · May 4, 2017

Redux Thunk teaches Redux to recognize special kinds of actions that are in fact functions.

When an action creator returns a function, that function will get executed by the Redux Thunk middleware. This function doesn't need to be pure; it is thus allowed to have side effects, including executing asynchronous API calls. The function can also dispatch actions.

The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.

If Redux Thunk middleware is enabled, any time you attempt to dispatch a function instead of an action object, the middleware will call that function with dispatch method itself as the first argument.

And then since we “taught” Redux to recognize such “special” action creators (we call them thunk action creators), we can now use them in any place where we would use regular action creators.

Check this great answer from Dan Abramov himself, it covers everything: https://stackoverflow.com/a/35415559/5714933

Also check these links for more info:

https://github.com/gaearon/redux-thunk#motivation http://redux.js.org/docs/advanced/AsyncActions.html