Search code examples
reactjsreduxsaga

Why should I use Redux Saga?


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.


Solution

  • 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.