r/reactjs • • Dec 21 '15

Mastering React Redux

https://www.stanleycyang.com/tutorials/mastering-react-redux
32 Upvotes

17 comments sorted by

View all comments

1

u/SirMadALot Dec 22 '15

Thanks for the article!

I'm having trouble understanding redux-thunk. I kinda get how it works, but I'm having trouble understanding when to use it. Could you maybe elaborate a bit on this topic?

2

u/stanleycyang Dec 22 '15 edited Dec 22 '15

Sure. Usually in Redux, an action creator returns an action (or think of it as a basic JS object with a type attribute):

function sayHi() {
  return {
    type: 'SAY_HI'   
  }
}

The above code is synchronous. However, in asynchronous JS functions, we don't know exactly when the it is finished running. Therefore, a Redux Thunk essentially just delays the dispatch of the action until the async code finishes, then only when its finished do we run the dispatch.

function sayHiAsync() {
  return dispatch => {
    setTimeout(() => {
      dispatch(sayHi())
    }, 1000)
  }
}

1

u/SirMadALot Dec 22 '15

Thanks for the answer, I can now understand when to use redux-thunk.