Shivam Thakur
Shivam Thakur

Reputation: 73

why setState only updates on mutating original state

interface list {
name: string,
id: number,
marks: number
}

component state :

{
listOfStudents: list[],
}

now on some event, where marks is modified for a student with given name and following handler function, the following doesn't work

currentList = this.state.listOfStudents;
//find the list object with the given name
listToModify = currentList.map(item, ....=> item.name === event.name);
// update its marks
listToModify.marks = event.marks;
//set new state
this.setState({listOfStudents: currentList});

But the following works:

//get a copy of the object
currentList = [...this.state.listOfStudents];
//find the list object with the given name
listToModify = currentList.map(item, ....=> item.name === event.name);
// update its marks
listToModify.marks = event.marks;
//set new state
this.setState({listOfStudents: currentList});

I didn't have to add new data but modify an existing one, why is mutation required in such a case?

Upvotes: 0

Views: 68

Answers (1)

buzatto
buzatto

Reputation: 10382

for a given state that is an object or array, react uses only its reference to compare and decide if it will update state, it doesn't do deep comparision between objects values.

the first case you are passing the same reference, therefore there is no update state. actually, if you modify the array at first example, that's actually mutating state directly.

second case you are cloning into a new fresh array, which holds a different reference. since the reference is different from previous array, react now update its state. that's actually the right approach to update state when dealing with arrays/objects.

Upvotes: 1

Related Questions