Search code examples
reactjsredux

React Redux, why not we dispatch success and Fail action from event handler


I am learnig react and react redux, I just want to know that, suppose I have sign in page, there onSubmit we dispatch action SIGN_IN (of redux) , on action then we dispatch SIGNIN_SUCCESS and SIGNIN_FAILURE. So I just want to know that insted of handling SIGNIN_SUCCESS and SIGNIN_FAILURE on actions, can I handle it on submit handler function of Components.

So In this way I don't need redux think middleware, And there will be only sync actions.

Is this a good approch?


Solution

  • It's possible, but I can think of some disadvantages for this approach:

    • Separation of concerns, or the general intended structure of react-redux apps, envisions dealing with async actions outside of components. Async actions can potentially do complex things and it's cleaner to keep this out of components. They don't need to know about the details of handling errors on sign in (for example).
    • Reusing this event handler would need to be react custom hook (since it uses dispatch), tying it into react for no real reason. Other places in your app might want to dispatch a signIn thunk as well.
    • Thunks have quick and easy access to getState. If that is needed, it's a bit more cumbersome to do the same in react and a bit weird to use useSelector with the entire state.
    • Since redux-toolkit is now the recommended way to use redux, the createAsyncThunk it offers makes the typical thunks more concise. You get the pending/fulfilled lifecycle around a promise out-of-the-box. It's probably better to rely on this rather than re-inventing classic thunks in a different way (what you had in mind with sync actions).