Why should a Redux reducer be free of side effects?

I use Redux in my React app and something is bothering me. The documentation for Redux clearly states that the gearbox must be stateless. You often see such examples:

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 even required? JavaScript is single threaded. In the gearbox there is no chance of a race condition. As far as I can tell, the Redux repository is able to return the current state of the store, so it seems strange that so much attention is paid to pure functions.

+5
source share
3 answers

The case for pure functions is done in the documentation. Of course, you can write reducers with unclean functions, but:

Development features such as time travel, recording / playback, or hot reloading will be disrupted.

If none of these functions gives you advantages or interests you, then by all means write unclean functions. However, the question then becomes, why use Redux?

+6
source

Just because single-threaded does not mean that it is not asynchronous, but it really is. Side effects have nothing to do with threading, and it all depends on how your object behaves the way its API says it will: if it had a state, you might have different behavior depending on how many calls were made for it, and what data was transferred for each call, instead of being an object with constant behavior, regardless of when you call it.

The important part is "always behave exactly the same as for the same entrance." Adding and using state is almost literally a promise that this will not happen.

+2
source

Because

Redux is a predictable container for JavaScript applications.

Focus on "predictable."

Adding side effects makes it un predictable

+1
source

Source: https://habr.com/ru/post/1245099/


All Articles