The concept of Shallow Merging is very simple. As it's simple, so most of the people ignore this or even in paid courses some instructor will not talk about this concept much.
But, as a React-Developer, this concept is very crucial if you love ๐งก to code in class component.
So, let's go !!
Shallow Merging :
Shallow Merging means it only cares about the first level of the object and will replace anything deeper than the first level.
Let's understand with an example :
state={
music : "K-Pop",
band : {
bandOne: "BTS",
bandTwo: "BlackPink"
}
}
So, if we use setState like mentioned below :
this.setState({ band, { bandTwo: โEXOโ } })
So, this results into below output :
state={
music : "K-Pop",
band : {
bandTwo: "BlackPink"
}
}
SO, this is known as Shallow Merging. In this example, instead of updating the bandTwo value, it will update the band.
So, in order to prevent this, we have to use another method to set the state in React.
Method to solve this :
So, in order to solve this, we use one function here.
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
this.setState((prevState, currentProps) => ({
band : {...prevState, bandTwo : "EXO" }
)});
So this will have the intended effect. Here is how the state will look like :
state={
music : "K-Pop",
band : {
bandOne: "BTS",
bandTwo: "EXO"
}
}
Thanks for reading this article, hope this will clear the doubt.
Top comments (2)
This concept is awesome !!
The first example with the result after using the
setState
shouldn't be the following?:To be more precise instead of the
{bandTwo: BlackPink}
object to be the one above.