Shallow Merging in React

Jagroop Singh - Apr 24 '22 - - Dev Community

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"
           }

}
Enter fullscreen mode Exit fullscreen mode

So, if we use setState like mentioned below :

this.setState({ band, { bandTwo: “EXO” } })
Enter fullscreen mode Exit fullscreen mode

So, this results into below output :

state={
  music  : "K-Pop",
  band  :  {  
            bandTwo: "BlackPink"
           }

}
Enter fullscreen mode Exit fullscreen mode

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" }
)});
Enter fullscreen mode Exit fullscreen mode

So this will have the intended effect. Here is how the state will look like :

state={
  music  : "K-Pop",
  band  :  {  
             bandOne: "BTS",
             bandTwo: "EXO"
           }

}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this article, hope this will clear the doubt.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .