InterviewSolution
| 1. |
What are Pure Functions and how they are used in reducers? |
|
Answer» A Pure function is a function which : Consider the below example: Math.random(); // => 0.4011148700956255 Math.random(); // => 0.8533405303023756 Math.random(); // => 0.3550692005082965Even though we didn’t pass any arguments into any of the function CALLS, they all produced different output, meaning that `Math.random()` is not pure. Now consider the below add function doesn’t alter “a” or “b”, always returns the same output for the same input. The SECOND condition is that it should not produce any side effects. It basically means it should not change any external state. Consider, the below CODE. The function addNum changes the values of external “a”, so it’s not a pure function. var a = 10; function addNum(num) { a = 20; return num + a; } console.log(addNum(5)); //25 console.log(a); //20Reducers are Pure Functions as they don’t mutate the state. It generates a new state which is a copy of the old state. const initialState = { indPopData: [], }; const dataReducer = (state = initialState, action) => { LET newState; switch (action.type) { case types.GET_INDIA_DATA: newState = { ...state, indPopData: action.indPopData }; break; default: newState = state; } return newState; }; |
|