Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a pure reducer?

What I understand is that there is a concept of "Pure functions" which I got explained in this video and this question What is pure functions?

However I have encountered the term "Pure reducers" in the context of flux/redux I read on this link

But I'm not entirely sure how to apply this "pure concept" to reducers, what is a pure reducer?

like image 957
Adrian Forsius Avatar asked Mar 12 '23 05:03

Adrian Forsius


1 Answers

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;
 }
like image 75
Dhananjaya Kuppu Avatar answered Mar 15 '23 18:03

Dhananjaya Kuppu