Redux logo

Detect state mutation in Redux

Redux is one of the most popular state containers out there. It is well documented and simple to implement. It is one of the neatest paradigms I’ve ever worked with. Developer experience is just great, troubleshooting and debugging Redux driven applications is a breeze (in most cases). So what makes it so good? It is the 3 core principles of Redux that makes it so simple but powerful:

  • single source of truth – Redux state is stored in single object tree
  • state is read-only – state is never changed by directly referring to state variable, it is changed by dispatching Flux-like actions
  • changes are made with pure function – state is passed to pure function(called reducer is Redux world) and the new state is returned

In this short post I will focus on last point. Reducer must return new state, not a modified state that is passed to it, but completely new object. This ‘idea’ is taken from Functional Programming where Immutability is one of the core concepts. When you are working on any project, sometimes it can be not possible to deeply review code of your colleagues. It is good to have automated tools that would ensure your code quality, standards or paradigms are in line with what has been agreed by team.

To ensure that your reducers don’t mutate state you can use redux-immutable-state-invariant middleware. It will throw error in console whenever state mutation occur. This middle ware can save you headaches in situations when for example your time travel in Redux Devtools is not working as expected. One last thing. Be sure not to use it in production environment as it will slow down your app drastically,

I’ve set up sample repo to show how redux-immutable-state-invariant middleware works, you can find here. When you run it (npm start command) you will get a screen with two buttons. Click on ‘This button will mutate state’ button and observe console (I’ve used create-react-app package to scaffold this demo so you will also see error on screen, but if you use different setup you might not see any errors screen, only in dev tools). Output from console looks like this:

State mutation error in devtools conosle

Leave a Reply

Your email address will not be published. Required fields are marked *