0

I'm recently getting into React.js and learning with a small project.
While studying, I couldn't figure out clearly why I used react-saga or react-thunk.
It is said to process redux state value asynchronously.

But don't we already have async / await? Shouldn't we call api from a component file using async / await to get a value from the server and store it in the redux store?
I've seen a lot of articles on why to use react-saga, but the question hasn't been answered yet.

Why is there a clear reason to use redux-saga?

KimBenGon
  • 165
  • 1
  • 10

1 Answers1

2

Saga deals with more complex async flows. Thunk is the simple tool for async redux actions that is probably enough for 90% of projects. I'm a bit biased here because I think saga is often introduced as a shiny new tool into projects without an actual need. I have yet to see a project where they clearly needed saga (and not just thunk).

To your first question: Yes, we could handle async things in components and use async/await to dispatch actions around api requests, but it's bad design, since you're concerning the React component with things it shouldn't care about. It should contain display logic and be testable with only that.

Getting the data from api responses into the redux store should be handled outside of components because it's simply not a concern of the view rendering abstraction layer in your app.

timotgl
  • 1,301
  • 6
  • 14
  • Thank you for your reply. From a design perspective, is it right to import data from the api server when saga is running? Or should the reducer handle it? If the reducer processes it, the saga is not needed. – KimBenGon Dec 20 '19 at 09:46
  • 2
    @KimBenGon reducer should be pure so the fetch itself should be in the saga/thunk. If you are talking about a transformation of the received data then I would suggest creating a pure utility function that can be called at either of the two places. – Martin Kadlec Dec 20 '19 at 16:08