I wonder why Redux-Saga / Redux-Thunk solves side effects (even I don't know what side effects really is and how it affects ReactJS) better than normal Redux/ useReducer.
There is an normal example to handle calling api (as far as calling api is meant making a side effect)
Using normal redux/ useReducer:
const fetchData = async (offset?: number) => {
dataDispatch({ type: Data.REQUEST });
try {
const result: ResponseBase<undefined, DataModel> = await apiGetData(offset || 0);
if (result.responseCode.toString().startsWith('2')) {
dataDispatch({
type: Data.SUCCESS, payload: {
datas: result.dataArray || [],
pageable: result.pageable
}
})
}
}
catch (err) {
dataDispatch({
type: Data.FAILTURE,
payload: new Error(err.message || '')
});
}
};
useEffect(() => {
fetchData()
}, [])
Using Redux-Saga:
function* fetchData(offset: number) {
try {
const result: ResponseBase<undefined, DataModel> = yield call(apiGetData, offset);
yield put(DataSuccessAction(result.dataArray, result.pageable));
} catch (e) {
yield put(DataFailureAction(e))
}
}
#code in component
useEffect(() => {
DataRequestAction(10) // 10 is an offset
}, [])
I think result are the same for two implementation. But implementing the first one is clearer and easier. What are benefits of Redux-Saga in this circumstance? Does anybody explain it to me in detail? Thank in advance.
First of all it must be said that it's not correct to compare redux-saga
library and useReducer
hook. These are different tools for different cases.
useReducer
is a hook that allows you to implement redux like state for component without having redux or having complex local state management without connecting to your redux state (discussing use cases for that is out of your original question). It work on its own. You don't need redux
to use useReducer
.
redux-saga
is just a tool that gives you an approach to work with async code/complex actions' handlers. It works on top of redux
. So it extends redux functionality.
Here is an example how to use it with useReducer
. Github issue link.
Didn't check if it works though but still.
I think result are the same for two implementation. But implementing the first one is clearer and easier. What are benefits of Redux-Saga in this circumstance? Does anybody explain it to me in detail? Thank in advance.
You've answered your question by your own.
But it's possible to make first example more clean and easier to read. For example you can add action creators instead of generating object inside fetchData
function. And in example with saga
there is no if
statement that makes example with useReducer
ugly.
Ultimately, efficiency of code depends on how you write code (in most cases) but not on the library you use. Awful things can be done with any library or tool.