Immutable??

An immutable object is one whose content cannot be changed. An object can be immutable for various reasons, for example:

What are the benefits of Immutability?

  1. Easier Undo/Redo and Time Travel

When you are implementing word document in Javascript and you want to give features like redo/ undoes then you need to have different copies at a different time. We need to avoid mutation and should keep the references of older versions as well. just like version control system.

  1. Tracking Changes

when you are working on the complex object. In case Object is mutable one step/statement can change the structure or value of the object and later operation may lead incorrect data. Immutable data helps here.

  1. Determining When to Re-render in React

This point is regarding when to update the view of your page. If we have different copies of the object we can decide if 2 objects are changed then we will update. We need something to take a decision on otherwise we will keep updating the vie whenever some event has fired.

When I research about this topic, ‘Immutability’ is significant issue to improve code and application quality. If you want to make good use of immutability, you can find ‘Redux’.

Redux

Redux is a predictable state container for JavaScript apps.

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.

Redux1-1

https://opentutorials.org/module/4078/24935

Simple example

redux - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers

<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.1/redux.min.js"></script>
let store = Redux.createStore(reducer);
function reducer(state, action) {
  if (state === undefined) {
    return { color: 'yellow' };
  }
}
let state = store.getState();
store.dispatch({ type: 'CHANGE_COLOR', color: 'red' });
let newState;
if (action.type === 'CHANGE_COLOR') {
  newState = Object.assign({}, state, { color: 'red' });
}
return newState;

redux1-2

store.subscribe(red);

Reference

https://developer.mozilla.org/en-US/docs/Glossary/Immutable

https://www.cronj.com/blog/why-immurability-is-so-important/

https://redux.js.org/introduction/getting-started