Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a Redux reducer have to be side-effect free?

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.

like image 218
Max Avatar asked Mar 15 '16 16:03

Max


People also ask

Should reducers have side effects?

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 .

Why does the reducer have to be pure?

Pure reducers have no side effects and enable things like time-travelling. They make reasoning about application behavior easier.

How do you handle side effects in Redux?

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.

Why do we need reducer in Redux?

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.


1 Answers

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?

like image 54
Brett Avatar answered Oct 02 '22 12:10

Brett