Redux has reducers tasked with transforming the state across the application. They are pure functions, which is a function that does not modify variables outside of its scope or depend on them. They are given the same parameters and the output should be the same every time.
Importantly they do not mutate the parameters or make any API calls. This will prevent side effects from happening in your application. They get the previous state and action which is transformed to return a new state.
Below are a few examples on preventing mutation:
Using Array.prototype.concat
- returns a new array or you can use ES6 spread operator ...
in a new array.
Below is an example of using the ES6 spread operator instead.
Handle object transformation
Don’t directly change the oldState
parameter object, use a new object {}
or Object.assign
in the return.
Below the currentObject
and newState
are merged if they have similar properties the right most parameter
will have priority. It then returns a new object.
Below is a way to remove an item from an array without mutating it.
ES6 spread operator example below: