Why should objects in Redux be immutable? I know that some frameworks such as Angular2 will use onPush and can take advantage of immutability to compare states of views for faster rendering, but I am wondering if there are other reasons as Redux is framework agnostic and yet it mentions within its own docs to use immutability (regardless of the framework).
Appreciate any feedback.
Greate article https://medium.cobeisfresh.com/how-redux-can-make-you-a-better-developer-30a094d5e3ec
Redux is a small library that represents state as (immutable) objects. And new states by passing the current state through pure functions to create an entirely new object/application states.
If your eyes-glazed over there don't worry. To sum up, Redux does not represent changes in your application's state by modifying objects ( as you would with object-oriented paradigms). Instead state changes are represented as the difference between the input object and the output object (
var output = reducer(input)
). If you mutate eitherinput
oroutput
you invalidate the state.To sum up another way, immutability is a requirement of Redux because Redux represents your application state as "frozen object snapshots". With these discrete snapshots, you can save your state, or reverse state, and generally have more "accounting" for all state changes.
State of your app is only changed by a category of pure functions called reducers. Reducers have 2 important properties:
function name(state, action) {}
, so it makes it easy to compose them:Assume the state looks like this:
We want to increment the count, so we make these reducers
Note the use of
Objectd.assign({}, ...)
to create an entirely new objects in each reducer:Assuming we have wired up Redux to these reducers, then if we use Redux's event system to trigger a state change ...
...Redux will call:
NOTE:
action
is fromdispatch()
Now
theNewState
is an entirely new object.Note: You can enforce immutability with a library (or new language features), or just be careful to not mutate anything :D
For a deeper look, I highly recommend you checkout this video by Dan Abramov (the creator). It should answer any lingering questions you have.
The following benefits of immutability are mentioned in Redux documentation: