I have been using Redux in my React app and something has been bothering me. The documentation for Redux makes it very clear that the reducer should be state free. You often see examples like this:
function reducer(state = { exampleState: true }, action) {
switch(action.type) {
case "ACTION_EXAMPLE":
return Object.assign({}, state, { exampleState: false });
default:
return state;
}
}
My question is why is this required at all? JavaScript is single threaded. There is no chance of a race condition inside the reducer. As far as I can tell, a Redux store is only capable of returning the current state of the store, so it seems weird that there is so much focus on pure functions.
Redux is inspired by functional programming, and out of the box, has no place for side effects to be executed. In particular, reducer functions must always be pure functions of (state, action) => newState .
Pure reducers have no side effects and enable things like time-travelling. They make reasoning about application behavior easier.
Redux handles data with as much purity as possible, but for most applications you can't avoid side effects. Side effects are required to interact with the world outside of your client application. Side effects, in this context, are any interactions with the world beyond your Redux application.
REDUCER: In redux, the reducers are the pure functions that contain the logic and calculation that needed to be performed on the state. These functions accept the initial state of the state being used and the action type. It updates the state and responds with the new state.
The case for pure functions is made in the author's documentation. Sure, you can write reducers with impure functions, but:
Development features like time travel, record/replay, or hot reloading will break.
If none of those features provide a benefit or are of interest you, then, by all means, write impure functions. However, the question then would become, why use Redux?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With