Last updated on May 6, 2020
In this blog post, you will learn another way of writing reduxReducer
function piece of State Management for front-end applications.
Introduction
If you have used redux
for your front-end application to apply state management techniques, then you must have come across this one.
As normally, we use Switch
syntax to write the Reducer
piece of code. Reducer
will help you to update the State
(single source of truth) of the application.
You will learn what’s an alternate approach we have to implement Reducer
function.
Another way of writing Redux-Reducer in StateManagement
WHY I emphasize this point here is that, writing the code that really works finally matters. But to keep code readable
that will help us in the long term maintaining the code-base.
For instance, to understand this piece will take up some code snippets along with the explanation.
You have almost used some sort of authentication where you have login
and logout
methods. You trigger those methods with Action
dispatching.
Once the action is dispatched from the UI component, that will get routed to Reducer
where the application state is maintained.
Our simple state representation of an object would be,
const initialState = {
is_loggin_in: false,
is_logged_in: false,
user: {}
};
1. Switch Syntax,
export const authReducer = (state = initialState, action) => {
switch (action.type) {
case LOGGING_IN:
return {
...state,
is_loggin_in: true
};
case LOGGED_IN:
return {
...state,
is_loggin_in: false,
is_logged_in: true,
user: action.payload
};
case LOGGED_OUT:
return {
...state,
is_loggin_in: false,
is_logged_in: false,
user: null
};
default:
return {
...state
};
}
};
authReducer
is the function name to update State
with the Switch
syntax.
2. Object Lookup,
The same authReducer
function you can re-write by having Object Look-up
way.
you have totally 3 cases from the above function, that you can have as a property of an object.
const authLookup = {
[LOGGING_IN]: {
...state,
is_loggin_in: true
},
[LOGGED_IN]: {
...state,
is_loggin_in: false,
is_logged_in: true,
user: action.payload
},
[LOGGED_OUT]: {
...state,
is_loggin_in: false,
is_logged_in: false,
user: null
}
}
export function authReducer = (state= initialState, action) => {
return authLookup[action.type] || state;
}
Now you might have noticed the huge difference, how we refactored our code that helps on code readability.
We have used Computed
property from JavaScript ES6
to dynamically evaluate the property name for action type that will return you the updated state.