lets start our topic with what is the Redux fast and why to use it before going to our main-point
Redux
lets first take why the Redux was created :
react applications is scale scaled very well,but ran into problems of predictable and maintainable state management when building larger applications.
but Redux solved this problem by using Flux architecture with creating actions, store and reducer features so the Redux is a global state management was created at 2015 by Dan Abramov to easily control the state all-over the project/app
to know more about flux architecture you can visit Flux architecture docs
How do we build Redux store ?
//creating the reducer to handle and manipulate the state
function exampleReducer(state = 0, action {
// then we make a switch case to change the state depending on the action type
switch(action.type) {
case 'increment':
return state += 0
case 'decrement':
return state += 0
default:
return state
}
}
//we creating a store first with create app store func from redux in
import {createStore} from 'redux'
const store = createStore(exampleReducer)
//then we adding the store to the provider in the index.js wrapping all the app
import {Provider, store} from redux;
<Provider store={store}> // the store is what we have created earlier
<App/>
</Provider>
now what is the flow of the redux?
1- the user do an action
2- the dispatched action goes to reducer
3- the reducer manipulate the state and save it in the store
4- the store send to the ui the new state to rerender
now At the time we will discuss our main topic and it's the middle wares
first will explain what is the middleware
the middleware it's allow us to intercept any action before it reach the reducer and apply any changes we need
and it used most in async, API calls like Redux-saga/Redux-thunk
how we apply the middleware
1- we need to use applyMiddleWare()
function from redux
// importing it first from redux
import {applyMiddleWare} from 'redux';
const middleWare = applyMiddleWare(middleWare-we-will-use)
// then we can add it to the store instance we made eariler
const store = createStore(reducer, middleWare)
now let's explain what is the redux-saga
Redux-saga is a middleware library that helps with the api calls using the genrator function
now lets see how to add saga in our store
// remember the applyMiddleWare we've created we import the createSagaMiddleware from redux-saga
import createSagaMiddleware from 'redux-saga'
const saga = createSagaMiddleWare()
const sagaMiddleWare = applyMiddleWare(saga)
const store = createStore(reducer, sagaMiddleWare)
sagaMiddleware.run(mySaga) // the rootSaga function
// example for the saga file
fucntion* sagaExample() {
try {
const response = yield call(the_api_func) // to call the api function to get it's response
const data = response // to sotre the data from the api
yield put({type: 'DATA_RESPONSE', payload: data} // to dispatch the response action in the reducer
} catch(err) {
console.error(err) // or you can dispatch another action with error state
}
}
function* rootSaga() {
yield takeLatest('DATA_REQUEST_TYPE', sagaExample)
// or you can use takeEvery insted of takeLatest
yield takeEvery('DATA_REQUEST_TYPE', sagaExample)
}
// note that the redux-saga dosn't need to return a function in it's action creator
now, What is the Redux-thunk And how we use it?
reudx-thunk is a returned fucntion in the action creator
or
is an action creator function that return a function
lets see how we use it
// same as redux-saga we need to apply the Thunk middleWare
import thunk from 'redux-thunk'
const thunkMiddleWare = applyMiddleWare(thunk)
const store = createStore(reducer, thunkMiddleWare)
// now lets create the action creator with the thunk middleware
function fetchTodo(todoId) {
return async (dispatch) => {
// you can use api here or any kind of logic
const response = await fetch(`/fakeApi/todo/${todoId}`)
const data = response.json()
dispatch(todosLoaded(data.todos))
}
}
when we need to use them?
Redux-Thunk:
we will use thunk in some small project that we need to integrate with the API and read the state in many components
but in the big scale projects using thunk would end up with promises callback hell
Redux-saga:
it's alot better in big scale project because it's easy to debug and could control the state easier with generator functions because of its returned iterable object that we can stop or control the actions when ever we want
now lets gather up what we say and compare between them
Redux-thunk:
1- action creator must return a function
2- it's can using promises with async functions
3- easy to learn comparing to redux-saga
4- could end up with promise callback hell in large scale project
Redux-saga:
1- action creator doesn't need to return a function
2- it uses a ES6 generator function* features
3- have hard learning curve because of learning the generator function features
4- easy to maintain in largescale project
thanks for your time and hope that article was useful and helpful for you
for more detailed information you can see:
Redux Documentation
Redux-saga Documentation
Redux-thunk Documentation
Top comments (0)