Does using map in setState satisfy immutability?

In one of the exercises, Mosh uses the following code to toggle a flag on a specific array item:

const movies = […this.state.movies];
const index = movies.indexOf(movie);
movies[index] = { …movies[index] };
movies[index].liked = !movies[index].liked;

My question is whether I can use something like this instead:

const movies = => {
return m._id === movie._id ? { …m, liked: !m.liked } : m;

Are we doing a shallow copy of all array elements except for the element of interest in both cases?


I think so, yes. I’m not sure about performance though. Could you compare both approaches with - say - 10000 movies trying to toggle the first movie in one run and the last in another?

const movies = => {
return m._id === movie._id ? {m.liked: !m.liked } : m;

do not need to copy m inside map function. because map funtion is a funcional programming style, it copied array for your already.

in this case, it should be fine.

however in real project programming you need to check the object and the object’s property you use is empty or not all the time. Because the movies’ data is coming from the server end. It is not reliable.

I will code this way:

import _ from “lodash”;

const movies = .cloneDeep( || [];
const index = movies.indexOf(movie);
.isEmpty(movies[index]) && _.isEmpty(movies[index].liked){
movies[index].liked = !movies[index].liked;

I’m not sure if it’s not a good idea to deepClone() members of a React state. Wouldn’t React think every single movie was changed and perform unnecessary rerenders, at least in vDOM? And besides that deep clones can be far more expensive than shallow copies.