in JavaScript, separate objects with the same keys and values are not equal to each other:
console.log({name: "Joe"} === {name: "Joe"})
// false
console.log({name: "Joe"} == {name: "Joe"})
// false
objects are pass by reference instead of pass by value.
a shallow comparison of objects checks that for each key, the value is strictly equal between the two objects.
two objects will never be strictly equal to each other, but they might be shallow equal.
a shallow comparison of arrays checks that for each index, the value is strictly equal between the arrays.
the default behavior of a component is to re-render any time props or state have changed. additionally, when a component re-renders, its children will re-render by default, regardless of whether they have new props.
shouldComponentUpdate
tells a component whether to re-render given upcoming props and state. for the default React.Component
, shouldComponentUpdate
always returns true, regardless of what props and state are.
(I made this diagram based on my own understanding, it might not be totally correct.)
a component only passes new props down to its child component via successive calls to render()
. suppose the following situation:
GrandParent
, Parent
, and Child
Grandparent
passes count
down from its state to Parent
as a prop, which passes it as a prop to Child
GrandParent
is a PureComponent, while Parent
is a regular component with shouldComponentUpdate
always returning false
.GrandParent
's state changes, it passes a new prop down to Parent
, but because Parent
's shouldComponentUpdate
returns false
, it never renders and thus it never passes down the new prop to Child
!automatically implements a shouldComponentUpdate
that does a shallow comparison of props and state. PureComponent gives a warning if you implement shouldComponentUpdate
yourself.
skips rendering children in the tree automatically, so they must be "pure" as well. (I don't understand this part.)
a version of PureComponent for functional components. it's an HOC, so you can just pass your component to React.memo()
to get a new component.
it's called memo because it memoizes the element and determines whether to re-render or to just return the memoized element, based on shallow comparison of props.
to customize memo()
, you can implement an areEqual
function: