React Redux Tutorials - 6 - Reducers


Reducer

  • specify how the app's state changes in response to actions sent to the store.
  • Reducer is a function that accepts state and actions as arguments, and returns the next state of the application.
  • (previousState, action) => newState
  • // (1) define a default state
    // state has to be represented by a single object.
    const initialState = {
      numOfCakes: 10
    }
    
    // initialState is passed in as an argument to the reducer function
    
    // (2) define a reducer function 
    // (previousState, action) => newState
    const reducer = (state = initialState, action) => {
      switch(action.type) {
        case BUY_CAKE: return {
          numOfCakes: state.numOfCakes - 1
        }
        // ! we are not mutating the state object but return a new object.
    
        // if there was an action which we haven't accounted for
        default: return state 
      }
    }
    In reality, your state object might contain more than one property. That is why it is always safer to first create a copy of the state object and then change only the properties that need to.
    To make a copy of the state object, we use the spread operator (...state). We are asking the reducer to first make a copy of the state object and then only update the numOfCakes. If there were other properties they would remain unchanged.
    const reducer = (state = initialState, action) => {
      switch(action.type) {
        case BUY_CAKE: return {
          ...state, 
          numOfCakes: state.numOfCakes - 1
        }
        default: return state 
      }
    }