Skip to content

Commit cc3f3c0

Browse files
committed
Implement shouldComponentUpdate to avoid re-renders after the image has been displayed
1 parent df47147 commit cc3f3c0

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/components/LazyLoadImage.jsx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,42 @@ class LazyLoadImage extends React.PureComponent {
2323
this.updateVisibility(nextProps.scrollPosition);
2424
}
2525

26+
getRelevantProps(nextProps) {
27+
const keys = Object.keys(nextProps);
28+
29+
if (!this.state.visible) {
30+
return keys;
31+
}
32+
33+
const propsToIgnoreAfterVisible = {
34+
afterLoad: true,
35+
beforeLoad: true,
36+
placeholder: true,
37+
threshold: true,
38+
scrollPosition: true
39+
};
40+
41+
return keys.filter(key => !propsToIgnoreAfterVisible[key]);
42+
}
43+
44+
shouldComponentUpdate(nextProps, nextState) {
45+
if (this.state.visible !== nextState.visible) {
46+
return true;
47+
}
48+
49+
const keys = this.getRelevantProps(nextProps);
50+
51+
for (let i = 0; i < keys.length; i++) {
52+
const key = keys[i];
53+
54+
if (this.props[key] !== nextProps[key]) {
55+
return true;
56+
}
57+
}
58+
59+
return false;
60+
}
61+
2662
componentDidUpdate() {
2763
if (this.refs.placeholder) {
2864
const boundingBox = {

0 commit comments

Comments
 (0)