×

Html & Html5

The World's best Software Development Study Portal

Redux Reducers:Pure Functions


Pure Functions:


A function is a process which takes inputs called arguments, and produces some output known as return value.

A function is called pure if it abides by the following rules:

  • A function returns the same result for same arguments.

  • Its evaluation has no side effects, i.e., it does not alter input data.

  • No mutation of local & global variables.

  • It does not depend on the external state like a global variable.


  • Reducers:


    Reducers are a pure function in Redux. Pure functions are predictable. Reducers are the only way to change states in Redux. It is the only place where you can write logic and calculations. Reducer function will accept the previous state of app and action being dispatched, calculate the next state and returns the new object.

    The following few things should never be performed inside the reducer −

  • Mutation of functions arguments

  • API calls & routing logic

  • Calling non-pure function e.g. Math.random()






  • How do you write reducers in Redux?


    The reducer takes two parameters:
  • the current state

  • and action.

  • This means that if provided the same state and action,your reducer must always return the same new state object. You need to have an initial value so that when Redux calls the reducer for the first time with undefined , it will return the initialState . Then the function uses a switch statement to determine which type of action it's dealing with.




    For Example:

        // 'add' is a pure function
    	
    	function add(a+b) {
    	    return a+b;
    	}
    
        // 'random' is an impure function
    
        function random(a) {
            return Math.floor(Math.random() * a) + 1;
    	}	
    	
    


    In the above example,'add'is a pure function means it always returns the same value.
    'random'is an impure function means it returns different values every time.



    It is bad practice to do the following inside our reducers:


  • Mutate the incoming state/action objects

  • Do things with side effects,such as network calls.

  • Call impure functions such as Date.now() or Math.random()