DEV Community

Cover image for Shallow Merging in React
Jagroop Singh
Jagroop Singh

Posted on

Shallow Merging in React

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.

Top comments (2)

Collapse
 
works profile image
Web

This concept is awesome !!

Collapse
 
elenabi profile image
elena-bi • Edited

The first example with the result after using the setState shouldn't be the following?:

  music  : "K-Pop",
  band  :  {  
            bandTwo: "EXO"
           }
}
Enter fullscreen mode Exit fullscreen mode

To be more precise instead of the {bandTwo: BlackPink} object to be the one above.