Here is my understanding, in terms of redux a reducer is a function which accepts two arguments (state, action).
1. state represents the current state of the application in store
2. action represents the action that triggered
Redux assumes that the reducers does accept the current state and don't mutate the state but returns the new state, depending on the action type. If it adheres and don't mutate the state then it is a pure reducer.
/********************** example of a pure reducer *****************************/
var initialState = {counter:0};
function counterReducer(state = initialState, action){
if (action.type === 'INCREMENT'){
// returns a new state incrementing a counter
return {counter:state.counter + 1};
}
else if (action.type === 'DECREMENT'){
// return a new state decrementing a counter
return {counter:state.counter - 1};
}
// returns the state as is
return state;
}
The above function has no side-effects whenever it is invoked with the same set of arguments it always returns the same output.
/********************* example of an impure reducer ***************************/
var initialState = {counter:0};
function counterReducer(state = initialState, action){
if (action.type === 'INCREMENT'){
// modifies state by mutating or incrementing the counter in state
state.counter++;
}
else if (action.type === 'DECREMENT'){
// modifies state by mutating or decrementing the counter in state
state.counter--;
}
// returns the state
return state;
}