An Interest In:
Web News this Week
- March 22, 2024
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To