I don't understand the use case of redux saga or the concept of "side effects". This is not for lack of trying, I want to understand, I really do. It seems like a popular design pattern but I just fail to see what it brings to the table.....
Take this example....
<button onClick={async () => {
setFetching(true);
try {
const result = await myApiCall();
setData(result.data);
} catch {
toast.error("Something went wrong!")
} finally {
setFetching(false);
}
}}>
{fetching ? (
<Spinner />
) : (
Click me!
)}
</button>
A simple button that loads some remote content and shows a spinner while it's going, it even shows a toast if there is a problem..... re-creating this functionality with redux saga would involve a lot more code. In fact the JSX part of the code would be the same length or even longer.
Please, I have been searching for the answer of "why saga" for many months. I can't sleep.
CodePudding user response:
Redux saga is most useful when you have long-running asynchronous tasks that you need to manage.
For example, I worked on a site that streams live tv. When you start playing a channel there's a multi-step process to get playback started, then there are tasks that need to be performed during playback (some based on timers, some event-driven), and tasks that need to be performed at the end of each program. And every piece of this must be able to cancel and clean itself up at a moment's notice if the user presses the channel up button, or if parental controls change, or if an emergency alert message comes in. This is difficult to orchestrate using promises, and sagas made it easier to do (though still not easy).
For stuff like your example, there is little to no benefit to using redux saga.
CodePudding user response:
In addition to the accepted answer, I just covered this topic in my recent talk The Evolution of Redux Async Logic. I'll paste in our recommendations from the last slide in that talk:
What use case are you trying to solve?
Data Fetching
- Use RTK Query as the default approach for data fetching and caching
- If RTKQ doesn't fully fit for some reason, use
createAsyncThunk
- Only fall back to handwritten thunks if nothing else works
- Don't use sagas or observables for data fetching!
Reacting to Actions / State Changes, Async Workflows
- Use RTK listeners as the default for responding to store updates and writing long-running async workflows
- Only use sagas / observables if listeners don't solve your use case well enough
Logic with State Access
- Use thunks for complex sync and moderate async logic, including access to
getState
and dispatching multiple actions