Recent time I've been interviewing a log and I often notice that understanding how an updating of a React components works is the complex theme. I see that's a little strange to ask this but you should know how it works to be an advanced React developer.
Let's start from first question:
Why component may be updated?
The first thing: state was updated. It doesn't matter if you your new state is the same as old - they have different links that's why React thinks they are different. And the second thing: props was updated. Here the situation is the same as with the state.
Now we understand why component may be updated. The next question:
What's going on with children components when a parent component was updated?
That's easy: they are updated too. That's all. It doesn't matter if props was the same - they have different links as the states too.
But we can avoid unnecessary updating if the values are the same. I mean if we have state like:
const state = {
name: 'John',
}
And after updating we have the same name: John
then why we should to update component?
So, the next question is:
How we can avoid unnecessary updating of a component?
There is two variants. First - we can use PureComponent
for class components or React.memo
for function components. PureComponent
shallowly compares the state and props and if there wasn't changes the component won't be updated. React.memo
works the same but it compares only props.
Here can be the next question:
How to deep compare the state and the props?
You shouldn't deep compare them because it is very inefficient and will harm performance. But if it is necessary then for the class components you can use shouldComponentUpdate(nextProps, nextState)
and compare your this.state
and this.props
deeply with nextState
and nextProps
.
For the functional components you can provide a custom comparison function as the second argument to the React.memo
. That function takes two parameters: (prevProps, nextProps)
.
Conclusion
I hope it will give you more understanding how updating of a React components works. Don't be hesitate to ask your questions about the topic or suggest idea for the next articles.
Happy coding and bye!
Top comments (3)
shouldComponentUpdate
does a shallow check, not deep equality. Often times it makes more sense to stringify the props so that they can be checked against each other as 1 object doesn’t equal another, even if the keys and values are the same.Hi, you’re right - it does a shallow check, I wrote the same. But I can’t agree with the stringifying the props because in that way you should parse and stringify data on every update and it can be very inefficient
I guess I misunderstood. This reads as if I need a deep comparison, I should use
shouldComponentUpdate
. Stringifying is not an expensive operation and it’s far less expensive than rerendering. How would you actually compare props and newProps then?