Reputation: 10035
I heard that it's better to do testing this way but I don't understand why. What purpose does it serve to build a new state each time something changes rather than mutating what is already there? Is it faster?
Upvotes: 0
Views: 37
Reputation: 15914
No it's not faster. Mutating the state directly is usually faster.
Returning a new state makes reducers easier to test and predictable (because there is no side effect), also
we can prevent some unexpected behaviors from happening. For example If you are using PureComponent
and you mutate state directly, you component may not update as you expected, because PureComponent
use ===
to compare props.
Consider the code below, we are trying to render a list:
// current state
const list = ['foo', 'bar']
// we mutate the state directly
list[1] = 'hihi'
// in shouldComponentUpdate of a PureComponent
props.list === nextProps.list // true
In this case the component will not be aware of the update.
In addition to PureComponent
, there are some optimizations in react-redux rely on this convention.
Upvotes: 1
Reputation: 6944
Take a read of the Redux docs on the issue, but basically it makes each update much more preditable, which makes everything from testing to rendering simpler.
Upvotes: 0