It is said that the reducer function used in useReducer is a pure function. If I'm not wrong, "Its behaviour depends only on its input parameters -- so calling it twice with the same input parameters has the same resulting effect." (from here). And also (from here):
A reducer should:
never mutate its arguments
never generate side-effects (no API calls changing anything)
never call non-pure functions, functions that change their output based on factors other than their input (e.g. Date.now() or Math.random())
I have two questions regarding this:
- Can any one explain why the reducer must be a pure function? e.g. what can go wrong if it returns two different outputs while receiving the same input? Or, what happens if it has side-effects?
- Consider the following sample code:
export function MyComponent(props: IPropTypes) {
const reducer = (prevState, action) => {
newState = deepClone(prevState);
newState.count = newState.count + props.count;
return newState;
}
const [state, dispatch] = useReducer(reducer, ....);
return (<div>
...
</div>)
}
Am I right that the above reducer is not a good reducer because it is also dependent on props (which is not its input)? Why is this a bad thing?