Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  39] [ 5]  / answers: 1 / hits: 28223  / 6 Years ago, thu, january 11, 2018, 12:00:00

I have been learning React over the past few days, looking at a few tutorials and explanations regarding the different ways in which you can write different elements. However there is one I have been most curious about - the setState function to update/override the state properties of a component.



For example, imagine I have a class with the following:



class Photos extends React.Component {
constructor() {
super()
state = {
pictures: []
}
}

componentDidMount() {
// This is where the fetch and setState will occur (see below)
}

render() {
return {
<div className=container>
{this.state.pictures}
</div>
}
}
}


This example sees me fetch images from an API.



Given that I have performed my fetch, map and return for this function - I will then update the pictures: [] state array with the results gained in the API call.



My question stems from the differing methods I have seen regarding how to update/override the pictures state property.



I have seen it written in 2 varying ways:



1) This seems to be a very simple and easy to read method



this.setState({pictures: pics})



2) This is more complex but I have see it described as a more safe method



this.setState(prevState => ({
pictures: prevState.pictures.concat(pics)
}))


Could somebody please explain the merits of using either? I want to be consistent with code in the future, dealing with props and states etc, so the most versatile method would of course be preferred.


More From » html

 Answers
7

First things first, in your case the two syntaxes are entirely different, what you might be looking for is the difference between


this.setState({pictures: this.state.picture.concat(pics)})

and


this.setState(prevState => ({
pictures: prevState.pictures.concat(pics)
}))

To understand why the second method is a preferred one,you need to understand what React does with setState() internally.


React will first merge the object you passed to setState() into the current state. Then it will start that reconciliation thing. Because of the calling setState() might not immediately update your state.


React may batch multiple setState() calls into a single update for better performance.


Consider the simple case, to understand this, in your function you might call setState() more than once like:


myFunction = () => {

...
this.setState({pictures: this.state.picture.concat(pics1)})
this.setState({pictures: this.state.picture.concat(pics1)})
this.setState({pictures: this.state.picture.concat(pics1)})

...
}

which isn't a valid use case in a simple app but as the app gets complex, multiple setState() calls may be happening from multiple places, doing the same thing.


So now to perform an efficient update, React does the batching thing by extracting all the objects passed to each setState() call, merges them together to form a single object, then uses that single object to do setState(). According to the setState() documentation:



This form of setState() is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:


Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 1},
...
)

Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:


this.setState((state) => {
return {quantity: state.quantity + 1};
});

For more detail, see:



setState() - Other APIs - React.Component – React.



So if any of the objects contains the same key, the value of the key of the last object with same key is stored. And hence the update only happens once with the last value.


Demo Codesandbox


[#55484] Monday, January 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylor

Total Points: 334
Total Questions: 100
Total Answers: 111

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;