1.

What are reducers in redux?

Answer»

The reducers in redux are the pure functions that take the previous state and an action, and then it returns to the NEXT state.
(previousState, action) => newState

It is known as the reducer because they are the TYPE of function that would pass to Array.prototype.reduce(reducer, ?initialValue). It is very essential to ensure that the reducer stays pure.

To MAINTAIN this, there are few things that you should never do INSIDE the reducer:

  • Modify its argument
  • Make sure not to perform some side effects such as routing transitions and API calls
  • Call non-pure functions, e.g. Date.now() or Math.random().
Example

const initialState = { value: 0 }

function counterReducer(state = initialState, action) {
  // Check to see if the reducer cares about this action
  if (action.type === 'counter/incremented') {
    // If so, make a copy of `state`
    return {
      ...state,
      // and update the copy with the new value
      value: state.value + 1
    }
  }
  // otherwise return the existing state unchanged
  return state
}



Discussion

No Comment Found