Why Do We Need to Avoid Mutations?

Understand the need to avoid mutation.

We'll cover the following

The most important thing about reducers in Redux is that they should never mutate the existing state. There are several functions in JavaScript that can help when working with immutable objects. Before we look at those, however, let’s consider why this is so important.

Reason

One of the reasons behind the immutability requirement for reducers is due to change detection. After the store passes the current state and action to the root reducer, it and various UI components of the application need a way to determine what changes, if any, have happened to the global state. For small objects, a deep comparison or other similar methods might suffice. But if the state is large and an action has only changed a small fraction, we need a faster and better method to identify changes.

There are many ways to detect a change made to a tree, each with its pros and cons. Among the many solutions, one is to mark where changes were made in the tree. We can set a dirty flag, add a version to each node, or use reference comparison. The latter is the preferred Redux method.

Get hands-on with 1200+ tech skills courses.