Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 24, 2022 09:48 am GMT

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

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.


Original Link: https://dev.to/jagroop2000/shallow-merging-in-react-ffk

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To