By utilizing immutable data structures, we can write code that is easier to reason about, avoid mutation-related bugs, reduce complexity, and even gain some performance benefits along the way.
Before diving too far into Facebook's Immutable.js library, let's take a moment to examine some of the pains and obstacles that mutable data structures present.
Array to use Immutable.List in order to address a mutation-related "bug" caused by multiple objects "sharing" a mutable structure (array) by reference.
We're going to take a look at Facebook's immutable library. If you're new to the term immutable, they sum it up pretty well right here. You gain a lot of benefits from using immutable data structures.
I've set up an example here so we can take a look at one of the pains that using immutable data structures solves. Imagine we have a party and we have some guests and they're going to be eating food.
We ultimately want to know what food they ate. If we run this now we'll see that by default they've all just eaten the default menu. Let's have them eat some more food. John is going to decide to be healthy. He's going to eat a salad.
Jane, she's going to have some ribs. Bill, he gets a little out of control and he just starts eating and eating. He's going to have some Twinkies. Then also, he's going to eat some ribs and he's going to flush it all down with a hot dog.
Now, we'd hope that when we update this that this will reflect what each of them had eaten individually. But if we run this, we'll see -- and it looks like we had ribs on the mind here, change that to eat -- that this is reflecting that they all ate everything. That's the problem of mutable data structures is that here we have our default menu and when we create each guest we're assigning that to their food, we're just saying that by default.
Here, when we're saying this.foods.push, this ends up being a reference to the original array variable here. that shared mutable structure is being shared across each of the guest instances.
Now, let's take a look at how we might solve this by using immutable data structures. We'll begin by just pasting this party into this. We have this set up for a list party. Change this to reflect that. We have the immutable js library pulled in already, so let's take a look.
If we run this now, we'll see that these haven't changed at all. That's because when we say this.foods.push, this is no longer mutating this .foods, so we need to reassign that, this.foods equals this.foods.push and what push on the immutable list is going to do, it's going to return a new structure that represents the previous state with the added element.
We run that, now we can see that they are each reflecting what they ate individually, that's a quick, simple example as to why we might want to use immutable data structures.