Reputation: 566
In react documentation, it is written that:
For React-Redux, connect checks to see if the props returned from a mapStateToProps function have changed in order to determine if a component needs to update. To improve performance, connect takes some shortcuts that rely on the state being immutable, and uses shallow reference equality checks to detect changes. This means that changes made to objects and arrays by direct mutation will not be detected, and components will not re-render.
I think direct mutation is something like:
this.state.someState = 2
What does direct mutation mean here in the case of redux?
The second question that I have and not finding a satisfying answer to it is what can be the side effect of mutation or asynchronous behavior that is mentioned in the below documentation:
Side effects like mutation or asynchronous behavior will cause time travel to alter behavior between steps, breaking the application.
Upvotes: 0
Views: 320
Reputation: 5016
What does direct mutation mean here in the case of redux?
It means if your reducer mutates the state and returns it:
function myReducer(state, action) {
this.state.someState = 2
return state
}
then Redux won't think a change occurred because the returned value references the previous state. The reducer needs to return a new value.
what can be the side effect of mutation or asynchronous behavior
A side effect mutation looks like:
function myReducer(state, action) {
this.state.someState = 2
return { someState: this.state.someState + 1 }
}
Even though a new value was returned, the previous state was mutated in place. As a result, if you time-travel-debug to the previous state, you will not see its actual value, but instead 2
.
An example of an async side effect is:
function myReducer(state, action) {
return new Promise(res => {
return state + 2;
})
}
Any async behavior in your reducer will cause it to return a promise, which will show up in state and likely be invalid data for your components.
Upvotes: 1
Reputation: 101700
What does direct mutation mean here in the case of redux?
It means directly modifying the values in the Redux store:
reduxState.someProperty = 2;
or directly modifying anything contained within the Redux store.
To put it simply, you need to update the store by dispatching actions and using pure, synchronous reducer functions.
The second question that I have and not finding a satisfying answer to it is what can be the side effect of mutation or asynchronous behavior that is mentioned in the below documentation:
Mutation and asynchronous behavior are side effects, as it says in the text you quoted. It also states right in that text what the ill effects of this are: time travel (winding the state backwards and forwards) will not work correctly, and attempting to wind back to a previous state will actually give you something whose values are not consistent with what were actually in that previous state.
Upvotes: 1