Register to get access to free programming courses with interactive exercises

Immutability JS: React

State immutability is very important when it comes to working with React. It's easy to follow when working with primitive data types, but an untrained user may have difficulty with composite ones, such as objects and arrays. This lesson discusses the basic ways to partially update objects and arrays.

In addition to examples in pure JS, we'll also show examples using the immutability-helper library, which is designed to facilitate such operations. It's especially useful for upgrades where the JS code is too complex.

Arrays

Adding elements to an array

The simplest method is adding to an array:

const items = ['one', 'two', 'three'];
const item = 'four';
const newItems = [...items, item];
// ['one', 'two', 'three', 'four'];

If you want to add an element to the beginning, all you have to do is swap the elements of the array:

const newItems = [item, ...items];
// ['four', 'one', 'two', 'three'];

Using immutability-helper

import update from 'immutability-helper';

const state1 = ['x'];
const state2 = update(state1, { $push: ['y'] }); // ['x', 'y']

Deleting from an array

This is a more interesting example. If you want to remove an element from an array, you need to know what to remove. This means that each item in the collection must have an identifier. We can use good old-fashioned filtering to delete something.

const newItems = items.filter((item) => item.id !== id);

You may be wondering where the identifier inside the handler came from. And this is where closure comes to our aid.

See the Pen js_react_immutability_array_remove_element by Hexlet (@hexlet) on CodePen.

Note the way the handler is set: removeItem = (id) => (e) => { and its use of onClick={this.removeItem(id)}.

Using immutability-helper

const index = 5;
const newItems = update(items, {$splice: [[index, 1]]});

In clean JS, deleting using a filter is the best way. Using immutability-helper is difficult.

Changing an array

Unfortunately, if we don't any additional tools, the code for our solution will get too cumbersome. We're showing it here for reference, but you shouldn't do this in real code.

const index = items.findIndex((item) => item.id === id);
const newItem = { ...items[index], value: 'another value' };
const newItems = [...items.slice(0, index), newItem, ...items.slice(index + 1)];

I imagine I won't have to convince you that this is too much :)

Using immutability-helper

const collection = { children: ['zero', 'one', 'two'] };
const index = 1;
const newCollection = update(collection, { children: { [index]: { $set: 1 } } });
// { children: ['zero', 1, 'two'] }

As you can see, this method is much easier and cleaner. Recommended for use.

Objects

Adding to an object

This is just as simple as with arrays.

const items = { a: 1, b: 2 };
const newItems = { ...items, c: 3 };
// { a: 1, b: 2, c: 3 }

Or, if the key is calculated dynamically, you must do this:

const items = { a: 1, b: 2 };
const key = 'c';
const newItems = { ...items, [key]: 3 };
// { a: 1, b: 2, c: 3 }

Removing from an object

Destructuring comes to the rescue:

const { deletedKey, ...newState } = state;

Using immutability-helper

import update from 'immutability-helper';

const state = { a: 1, c: 3 };
const updatedState = update(state, {
  $unset: ['c'],
});
// { a: 1 }

Changing an object

Exactly the same as adding.

const items = { a: 1, b: 2 };
const newItems = { ...items, a: 3 };
// { a: 3, b: 2 }

Using immutability-helper

const data = { a: 1, b: 2 };
const key = 'a';
const newData = update(data, { [key]: { $set: 3 } });
// { a: 3, b: 2 }

Deep nesting

In the examples above, you can mostly make do with the standard JS tools' it's only more convenient to use third-party solutions in certain situations. This is the same in real code, especially if you consider React's recommendations and keep the state as flat as possible. But in some situations, the data that needs to be changed isn't on the surface, but deep within the structures. Unfortunately, in these situations, normal JS code will be bloated. And here you can't do without additional libraries.

import update from 'immutability-helper';

const myData = {
  x: { y: { z: 5 } },
  a: { b: [1, 2] },
};

const newData = update(myData, {
  x: { y: { z: { $set: 7 } } },
  a: { b: { $push: [9] } }
});
console.log(newData)
// => { x: { y: { z: 7 } }, a: { b: [ 1, 2, 9 ] } }

https://repl.it/@hexlet/js-react-immutability-helper

Equivalent options

immutability-helper isn't the only library for such tasks. Here are a few more popular ones:

  • immutable-js – based on persistent data
  • updeep – makes extensive use of mapping
  • immerjs – probably the most popular library in JS for working with immutable data

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.