Max
Max

Reputation: 15975

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.

Upvotes: 11

Views: 2878

Answers (3)

Brett
Brett

Reputation: 4269

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?

Upvotes: 9

Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9356

Because

Redux is a predictable state container for JavaScript apps.

Emphasis on 'predictable'.

Adding side effects makes it unpredictable

Upvotes: 1

Just because it's single threaded doesn't mean it's not asynchronous, but that's beside the point really. Side effects have nothing to do with threading and everything to do with making sure your object behaves the way its API says it will: If it had state, you could have different behaviour depending on how many calls were made to it, and what data was passed for each call, instead of being an object with constant behaviour regardless of when you call it.

The important part is the "always behave exactly the same way for exactly the same input". Adding and using state is almost literally a promise that this will not be the case.

Upvotes: 2

Related Questions