1
votes

I've always struggled to get my head around Redux-thunk, as it really don't understand what great purpose it serves. For example, here's a random Redux-Thunk example I found from a website:

export const addTodo = ({ title, userId }) => {
  return dispatch => {
    dispatch(addTodoStarted());

    axios
      .post(ENDPOINT, {
        title,
        userId,
        completed: false
      })
      .then(res => {
        setTimeout(() => {
          dispatch(addTodoSuccess(res.data));
        }, 2500);
      })
      .catch(err => {
        dispatch(addTodoFailure(err.message));
      });
  };
};

It's seemingly simple, addTodo is a function that takes in the title and userId and returns a function with dispatch as a parameter, which then uses dispatch once and then again for the response of the HTTP request. Because in this case Redux-Thunk is being used, you would just do dispatch(addTodo(x,x));

Why would I not just do something like this though?

function addTodo(dispatch, title,userId){
  dispatch(addTodoStarted());

  axios
    .post(ENDPOINT, {
      title,
      userId,
      completed: false
    })
    .then(res => {
      setTimeout(() => {
        dispatch(addTodoSuccess(res.data));
      }, 2500);
    })
    .catch(err => {
      dispatch(addTodoFailure(err.message));
    });
}

Then from anywhere, I can just call addTodo(dispatch, x, x);

Why would I use the Redux-Thunk example over my own?

1
already answered, please follow the link. stackoverflow.com/questions/34570758/…hazimdikenli

1 Answers

0
votes

Here are few points through which i will try to explain why should go with redux-thunk.

  1. Its middle ware so it will make dispatch and state object available in every action you define without touching you component code.

  2. When you pass dispatch function which is either from props or from mapDispatchToProps(react-redux) which creates closure. This closure keeps memory consumed till asyc operation finished.

  3. When ever you want to dispatch any action, after completing or in async operation you need to pass dispatch function and in this case you need to modify two files like your component and actions.

  4. If something is already available and tested with lot effort and community support why not use it.

  5. your code will be more readable and modular.

  6. Worst case for both approach, say after completing project, need to change thunk approach, you can easily mock thunk middle ware with your custom middle ware code and resolve it but in case of passing dispatch function it will refactoring all code and search and replace and find way to manage it.