Frontend Development 14 min read

Understanding Immutable Data Structures and Their Use in React and Redux

This article explains what immutable data structures are, outlines their advantages such as reduced complexity, memory savings, easy state rollback, and functional programming benefits, and demonstrates practical usage of Immutable.js in React components and Redux integration with code examples and best‑practice tips.

政采云技术
政采云技术
政采云技术
Understanding Immutable Data Structures and Their Use in React and Redux

1. What is Immutable?

Immutable Data is data that cannot be changed once created. Any modification returns a new immutable object, using Persistent Data Structures and Structural Sharing to avoid deep copies and improve performance.

2. Advantages of Immutable

2.1 Reduce Complexity and Avoid Side Effects

In JavaScript, objects are reference types, which can cause uncontrolled side effects when multiple variables reference the same memory. Immutable prevents this by always returning new objects on changes.

let obj1 = { name: '张三' };
let obj2 = obj1;
obj2.name = '李四';
console.log(obj1.name); // 李四

Using Immutable:

import { Map } from 'immutable';
let obj1 = Map({ name: '张三' });
let obj2 = obj1;
obj2.set({ name: '李四' });
console.log(obj1.get('name')); // 张三

2.2 Save Memory

Immutable uses structural sharing, reusing unchanged parts of the data structure.

import { Map } from 'immutable';
let obj1 = Map({ name: 'zcy', filter: Map({ age: 6 }) });
let obj2 = obj1.set('name', 'zcygov');
console.log(obj1.get('filter') === obj2.get('filter')); // true

2.3 Easy State Rollback

Each modification creates a new object, preserving history for undo/redo functionality.

import { Map } from 'immutable';
let historyIndex = 0;
let history = [Map({ name: 'zcy' })];
function operation(fn) {
  history = history.slice(0, historyIndex + 1);
  let newVersion = fn(history[historyIndex]);
  history.push(newVersion);
  historyIndex++;
}
function changeHeight(height) {
  operation(data => data.set('height', height));
}
let hasRedo = historyIndex !== history.length - 1;
let hasUndo = historyIndex !== 0;

2.4 Functional Programming

Immutable aligns with functional programming principles, making components easier to debug and compose.

2.5 Rich API

Immutable provides a full set of persistent data structures such as Collection, List, Map, Set, Record, and Seq, with methods for sorting, filtering, grouping, reversing, flattening, and creating subsets. See the official documentation for details.

3. Using Immutable in React

React re‑renders child components when parent state changes. Shallow comparison works for simple props, but fails for nested objects. Immutable enables cheap equality checks using === or Immutable.is , avoiding deep copy overhead.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Counter extends Component {
  state = { counter: { number: 0 } };
  handleClick = () => {
    let amount = this.amount.value ? Number(this.amount.value) : 0;
    this.state.counter.number = this.state.counter.number + amount;
    this.setState(this.state);
  };
  shouldComponentUpdate(nextProps, nextState) {
    for (const key in nextState) {
      if (this.State[key] !== nextState[key]) {
        return true;
      }
    }
    return false;
  }
  render() {
    return (
{this.state.number}
this.amount = input} />
+
);
  }
}
ReactDOM.render(
, document.getElementById('root'));

With Immutable, the component can compare states efficiently:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { is, Map } from 'immutable';
class Caculator extends Component {
  state = { counter: Map({ number: 0 }) };
  handleClick = () => {
    let amount = this.amount.value ? Number(this.amount.value) : 0;
    let counter = this.state.counter.update('number', v => v + amount);
    this.setState({ counter });
  };
  shouldComponentUpdate(nextProps, nextState) {
    if (Object.keys(this.state).length !== Object.keys(nextState).length) {
      return true;
    }
    for (const key in nextState) {
      if (!is(this.state[key], nextState[key])) {
        return true;
      }
    }
    return false;
  }
  render() {
    return (
{this.state.counter.get('number')}
this.amount = input} />
+
);
  }
}
ReactDOM.render(
, document.getElementById('root'));

4. Combining Immutable with Redux

Immutable can be used as the Redux store to keep the state tree immutable. Example of a counter reducer using Map and update :

import { Map } from 'immutable';
const ADD = 'ADD';
const initState = Map({ number: 0 });
function counter(state = initState, action) {
  switch (action.type) {
    case ADD:
      return state.update('number', v => v + action.payload);
    default:
      return state;
  }
}

When integrating with React‑Redux, mapStateToProps should return Immutable objects, and you can either rewrite combineReducers to work with Map or use the redux-immutable middleware.

// Custom combineReducers returning an Immutable Map
function combineReducers(reducers) {
  return function(state = Map(), action) {
    let newState = Map();
    for (let key in reducers) {
      newState = newState.set(key, reducers[key](state.get(key), action));
    }
    return newState;
  };
}

5. Points to Note When Using Immutable

Do not mix plain JavaScript objects with Immutable objects.

Make the entire Redux state tree an Immutable object.

Use Immutable everywhere except in pure presentation components.

Avoid frequent use of toJS() as it is performance‑heavy.

Selectors should always return Immutable objects to benefit from shallow comparison.

6. Conclusion

Understanding React's rendering mechanism, the diff algorithm, and immutable data structures is essential before applying performance optimizations such as code‑splitting, service workers, or SSR.

If any inaccuracies are found, contributions are welcome.

frontendJavaScriptReduxreactData StructuresImmutable
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.