Highlights on Redux
Written by zyydoosh, 20 Sep 2023
- State in Redux is "read-only", meaning we can't change it, well, sort-of. The only way to change the state is to 'emit' or dispatch an action (i.e object describing what happened) to the reducer (i.e the only place where you can manipulate the state)
- Since reducers are supposed to be “pure” (as in, they don’t change anything outside their scope) we can’t do any API calls or dispatch actions from inside a reducer.
- Dispatch an action, action is a plain object
dispatch({"var": "test"})
What if we need to dispatch this action multiple times!?…. wrap in an action creator
- Action creator creates an action; verbose enough 😀
function actionCreator() {return {"var": "test"}};
dispatch(actionCreator());
It’s funny that it’s called an action, but literally an object does nothing, want to execute logic?…. thunk function.
- Thunk is name for a function that gets called inside dispatch (differs from the action creator in that we use it to write logic, not just a wrapper for an object)
function thunk() {
// logic, api calls, side effects, etc..
}
As a programmer you love wrapping, like we wrap an action inside an action creator, wrap thunk in a thunk action creator 😀
- Thunk action creator; creates a thunk, fair enough 😀
function thunk() {
// logic, api calls, side effects, etc..
}
function thunkActionCreator () {return thunk();}
dispatch(thunkActionCreator());
What if we need to dispatch some action inside our function (thunk)?
What if the logic depends on the current redux root state?
What if we need to pass extra parameters?
- Thunk function always accepts dispatch, getState, optional extraParams
function thunk(dispatch, getState, [ extraParams ]) {
// logic, api calls, side effects, etc..
}
function thunkActionCreator () {return thunk();}
dispatch(thunkActionCreator());