I'm studying a React course at a point where the instructor is explaining about updating states and I cannot understand how those two snippets are really different internally, please see in the codepen links below:
Updates the state directly snippet
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
const updatedCounters = [...this.state.counters];
updatedCounters[0].value++;
};
}
Updates the state indirectly then save snippet
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleIncrement = counter => {
const updatedCounters = [...this.state.counters];
const index = updatedCounters.indexOf(counter);
updatedCounters[index] = {...counter};
updatedCounters[index].value++;
this.setState({ counters: updatedCounters });
};
}
In this lecture, the instructor explains that the first snippet does update the state directly. So my question is, if the first example, as the instructor says, updates the state directly, the only thing that prevents the second snippet from updating the state directly is the line below?:
updatedCounters[index] = {...counter};
If that is true, how does it works?