Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

How to create reducers in redux with react

How to create reducers in redux with react example

In this chapter, you will learn how to create reducers in redux with react.

Reducers:
Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.

Let’s create reducers for login

const initialState = {
    isEmployeeLoggedIn: false
};

const login = (state = initialState, action) => {
    var requestedDispatch = action.type;

    switch (true) {
        case /LOGIN/.test(requestedDispatch):
            return {
                ...state,
                isEmployeeLoggedIn: true
            };
        case /LOGOUT/.test(requestedDispatch):
            return {
                ...state,
                isEmployeeLoggedIn: false
            };
        default:
    }

    return state;
};

export default login;

As we can see in the above code snippet, we are passing 2 parameters in the arguments, the first one is the state and second is an action which is sent in the dispatch. We can put the switch case in the reduces to manage the specific action type which attached in the dispatch.

Leave a Reply

Your email address will not be published. Required fields are marked *