Learning React
Learning React
I always find myself modifying my component's state object directly. I think this is good for a simple web app. But, when the project become complex, I believe that practice will cause unknown bugs because some state were miss-out by the hooks inside React when the component renders.
Thus, It's not bad treating the state as immutable and use only the setState() method to modify state.
Example:
this.state = {
animals: ['pigs', 'goats', 'sheep']
}
Let's add a 'cow' in the array using array push().
this.state.animals.push('cows')
It looks good and meets the requirement. But it is actually touching the animals state directly.
Now you are thinking assigning it first to a variable before applying the push().
const animals = this.state.animals;
animals.push('cows')
But, this will not meet our real goal to not modify the state instantly.
animals and this.state.animals is still pointing to the same data in memory.
console.log(animals)
// ['pigs', 'goats', 'sheep', 'cows']
console.log(this.state.animals)
// ['pigs', 'goats', 'sheep', 'cows']
As a solution, we can use concat() as substitute for push(). Concat will create new array instead of using the source array state.
const animals = this.state.animals.concat('cows');
console.log(animals);
// ['pigs', 'goats', 'sheep', 'cows']
console.log(this.state.animals)
// ['pigs', 'goats', 'sheep'] <--- Untouched!
Then it's the time we use the setState() for modification of state.
this.setState({ animals: animals })