React state update with slice does not work

Viewed 28

I want to understand why the code can not work by copying the array from the state. checkboxes is an array of Booleans. I was of the opinion that if I assign checkboxes from state directly to tempCheckboxes it will be an alias and modifying an alias will indirectly impact state variable. But that is not the case. And I want to know why? Thanks for your help.

checkRow = (index, checked) => {
        let tempCheckboxes = this.state.checkboxes.slice();
        let all = true;
        tempCheckboxes[index] = checked;

        all = tempCheckboxes.every((isChecked) => this.isTrue(isChecked));
        this.setState((prevState) => ({ ...prevState, checkboxes: tempCheckboxes, checkAll: all }));
    }; 

Above code fails to work but following code works

checkRow = (index, checked) => {
        let tempCheckboxes = this.state.checkboxes
        let all = true;
        tempCheckboxes[index] = checked;

        all = tempCheckboxes.every((isChecked) => this.isTrue(isChecked));
        this.setState((prevState) => ({ ...prevState, checkboxes: tempCheckboxes, checkAll: all }));
    };

Edit : Reason for this question is in react we should not directly change the state with assignment but instead use setState to do so. In my opinion 2nd version of code is doing it. Earlier title for the question was not precise so changed it.

1 Answers

So the question is about javascript object reference.

Slice does not alter the original array, while the direct = which you are doing is creating a reference to the original object. So what you change in tempCheckboxes, will directly affect this.state.checkboxes.

In your second option tempCheckboxes will be a reference to the original this.state.checkboxes

In the first option you will refer to a new object in memory.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Related