What immutability is not

A common first mistake is conflating immutability with reassignment. Declaring a variable with let and pointing it at a new value is ordinary reassignment, not immutability:

let firstName = "Kingsley";
firstName = "John";

Switching to const prevents that second assignment and throws an error instead — but that still isn't immutability:

const lastName = "Silas";
lastName = "Doe"
// TypeError: Assignment to constant variable.

While React encourages treating state and props as immutable, immutability is a general JavaScript concept that React merely relies on.

Immutable data versus mutable structures

Immutable data cannot change its structure or the data inside it. A value set on a variable that cannot change becomes a kind of fact — a source of truth. Objects and arrays, by contrast, are mutable: their contents can be altered.

Consider a user object and a second object built from its properties:

let user = { name: "James Doe", location: "Lagos" }
let newUser = user

If the first user changes location, mutating user also affects newUser:

user.location = "Abia"
console.log(newUser.location) // "Abia"

That kind of unintended side effect is exactly what immutability is meant to avoid.

Pure functions and copy-on-write

To keep an object from being mutated, any method you use must return a new object — in other words, a pure function. A pure function has two properties:

  1. The returned value depends only on the inputs; it stays the same as long as the inputs do.
  2. It does not modify anything outside its own scope.

Object.assign() lets us write such a function: copy the later arguments into an empty object passed as the first argument and return it.

const updateLocation = (data, newLocation) => {
    return {
      Object.assign({}, data, {
        location: newLocation
    })
  }
}

updateLocation() is pure — given the original user, it returns a new user object with the updated location. The spread operator achieves the same result:

const updateLocation = (data, newLocation) => {
  return {
    ...data,
    location: newLocation
  }
}

Why React cares

In a typical React application the state is an object (and Redux uses an immutable object as the basis of its store). React's reconciliation process decides whether a component should re-render. If React cannot tell that a component's state has changed, it won't know to update the Virtual DOM.

Enforced immutability makes those changes trackable: React can compare the old and new state objects and re-render based on the difference. Directly updating state short-circuits this:

this.state.username = "jamesdoe";

React cannot be sure the state changed and so cannot re-render the component.

Enter Immutable.js

Redux reducers are meant to be pure functions: they should return a new object derived from the current state and the action rather than mutate the current state. The spread operator usually covers this, but a library called Immutable.js can do the same job and guarantees immutability through a performance-oriented API. Plain JavaScript immutability comes with several pitfalls; Immutable.js removes them.

The walkthrough below sketches a to-do app built with React and Redux, starting with the Todo component and its imports:


const { List, Map } = Immutable;
const { Provider, connect } = ReactRedux;
const { createStore } = Redux;
npm install redux react-redux immutable 
import { List, Map } from "immutable";
import { Provider, connect } from "react-redux";
import { createStore } from "redux";

With the component markup in place:

const Todo = ({ todos, handleNewTodo }) => {
  const handleSubmit = event => {
    const text = event.target.value;
    if (event.keyCode === 13 && text.length > 0) {
      handleNewTodo(text);
      event.target.value = "";
    }
  };

  return (
    <section className="section">
      <div className="box field">
        <label className="label">Todo</label>
        <div className="control">
          <input
            type="text"
            className="input"
            placeholder="Add todo"
            onKeyDown={handleSubmit}
          />
        </div>
      </div>
      <ul>
        {todos.map(item => (
          <div key={item.get("id")} className="box">
            {item.get("text")}
          </div>
        ))}
      </ul>
    </section>
  );
};

handleSubmit() creates new to-do items, and since creating items is the only operation, a single action suffices:

const actions = {
  handleNewTodo(text) {
    return {
      type: "ADD_TODO",
      payload: {
        id: uuid.v4(),
        text
      }
    };
  }
};

The payload carries the item's ID and text. That action is handed to the reducer:

const reducer = function(state = List(), action) {
  switch (action.type) {
    case "ADD_TODO":
      return state.push(Map(action.payload));
    default:
      return state;
  }
};

connect builds a container component that plugs into the store, using mapStateToProps() and mapDispatchToProps():

const mapStateToProps = state => {
  return {
    todos: state
  };
};

const mapDispatchToProps = dispatch => {
  return {
    handleNewTodo: text => dispatch(actions.handleNewTodo(text))
  };
};

const store = createStore(reducer);

const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Todo);

const rootElement = document.getElementById("root");

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
);

mapStateToProps() supplies the store's data to the component, while mapDispatchToProps() exposes action creators as props by binding the action.

The reducer initializes state with List from Immutable.js:

const reducer = function(state = List(), action) {
  switch (action.type) {
    case "ADD_TODO":
      return state.push(Map(action.payload));
    default:
      return state;
  }
};

Think of List as a JavaScript array — hence .push() works on state. Updates use a Map, recognizable as an object. Neither Object.assign() nor the spread operator is needed, the current state is guaranteed not to change, and deeply nested state no longer requires spread operators at every level.

Trade-offs and takeaways

Immutable state lets code detect a change quickly, without a recursive comparison over the data. The cost is that copying large data structures can bring performance problems. But applications need data to change to stay dynamic; immutability governs how it changes, making state changes traceable and telling you which parts of the application should re-render. The concept is confusing at first — errors from mutated state are often the clearest teacher.

Further reading

  • Immutability in React and Redux
  • Immutablejs 101 – Maps and Lists
  • Using Immutable.js with Redux