Search⌘ K
AI Features

Immutable Redux

Explore how to use ImmutableJS in Redux reducers to handle state immutably and efficiently. Understand replacing Object.assign with state.set and setIn methods for cleaner code and better performance. Learn to convert between ImmutableJS and plain JavaScript cautiously to preserve app speed while managing complex nested states.

We'll cover the following...

we make the initial state in our reducer an immutable object by using the fromJS function! We simply wrap the object that we assign to initialState in fromJS like so:

// reducer.js
/* … */
import { fromJS } from 'immutable';

var initialState = fromJS({
  /* … */
});

/* … */

Now we need to rework our reducer. Since our state is now immutable, instead of doing Object.assign({}, state, { /* … */ }) everywhere we can simply use state.set!

Let’s showcase this on the CHANGE_LOCATION action. This is what our reducer looks like right now:

case 'CHANGE_LOCATION':
	return Object.assign({}, state, {
	  location: action.location		
	});

Instead of doing this whole assigning business, we can simply return state.set('location', action.location)!

 ...