'Where should i handle sort in redux-saga?

I want to sort the data received from an api. Should I sort in the saga function and then save it to reducer? or Sort the data just before updating the store in reducer? or Should I sort in UI before rendering?



Solution 1:[1]

Depends.

Lot's of it comes to personal preference, some people prefer to do as much as they can in a saga and have reducers as simple as possible, others prefer to use sagas only for side effects and keep most data transformations to the reducers.

Most of the time it doesn't matter much, but in some cases there are things to consider. For example, if you know an action is going to get dispatched from multiple places and you will want to sort the data in each case, it might make more sense to do the sorting in the reducer, rather than doing it multiple times at those different places where the actions are being dispatched.

I found that for such data transformations it is best to have an utility function that will do the job. You can then call this function in either saga or reducer - it will be nicely "hidden" in whichever place you decided to put it to and it will also be easy to switch it to the other place if needed.

You also mentioned components and you are right, often times you will want to do transformations such as sorting during render and not when the data are stored, especially when e.g. the sorting depends on another application state like selected sort option. If you have a connected component, use reselect selectors to memoize such result so you are not sorting the same data again and again on every render. If it is some transformation done deeper in the react tree you can't handle with reselect, use something like memoize-one (class components) or use useMemo (function components) for the same effect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1