Add Data to a List without Mutations

Share this video with your friends

Send Tweet

In this lesson, we’ll create a utility function to add items to a list, avoiding mutation by returning a new array. We’ll verify this behavior by creating unit tests with Jest.

Anthony
Anthony
~ 8 years ago

I like that you stick to not mutating the original object, but maybe a small comment on why that's important or the reasoning behind it would be helpful for others as well.

Andy Van Slaars
Andy Van Slaars(instructor)
~ 8 years ago

Anthony,

Thanks for the feedback. I'll leave some reasons here in case anybody else is looking for it.

Immutable data structures and pure functions make code easier to test and cut down on unexpected behavior that can arise when data is changed in place. In the case of React specifically, immutable data also makes it easier to optimize rendering passes by comparing object references in shouldComponentUpdate or when using React.PureComponent

Hope this helps clear this up.

Thomas Greco
Thomas Greco
~ 8 years ago

For some reason, npm test doesn't seem to be working for me. I just spent quite a bit of time trying to re-install the project, and I even tried to run it in seperate create-react-app application's i have built and for some reasons it gets stuck at Determining test suites to run.... Any feedback would be appreciated :)

Andy Van Slaars
Andy Van Slaars(instructor)
~ 8 years ago

Thomas,

I can't reproduce this, so I'm guessing, but this sounds like it could be a problem with watchman. Maybe check out this issue discussion and try addressing watchman directly.

https://github.com/facebook/jest/issues/1767

I'd be curious to know is this fixes it for you. I hope this helps!

Fabio Albertin
Fabio Albertin
~ 8 years ago

That solved it for me. I think it'd be worth including this in video 1.

Iavor Dekov
Iavor Dekov
~ 7 years ago

I like that you stick to not mutating the original object, but maybe a small comment on why that's important or the reasoning behind it would be helpful for others as well.

I was thinking the exact same thing; thanks for the explanation Andrew!