Last active
March 26, 2019 15:49
-
-
Save fedyk/f9ded4d385dcd289a3c2954ee746edef to your computer and use it in GitHub Desktop.
Why my `PureComponent` is re-rendered?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyComponent extends React.Component<IProps> { | |
shouldComponentUpdate(nextProps, nextState) { | |
const nextPropsKeys = Object.keys(nextProps) | |
const propsKeys = Object.keys(this.props) | |
if (nextPropsKeys.length !== propsKeys.length) { | |
console.warn(`[MyComponent]: Mismatch in prop's keys`) | |
return true; | |
} | |
for (let i = 0; i < nextPropsKeys.length; i++) { | |
const key = nextPropsKeys[i]; | |
if (nextProps[key] !== this.props[key]) { | |
console.warn(`[MyComponent]: nextProps.${key} is not equal to the current value. This causes re-render`) | |
return true; | |
} | |
} | |
const nextStateKeys = Object.keys(nextState) | |
const stateKeys = Object.keys(this.state) | |
if (nextStateKeys.length !== stateKeys.length) { | |
console.warn(`[MyComponent]: Mismatch in state's keys`) | |
return true; | |
} | |
for (let i = 0; i < nextStateKeys.length; i++) { | |
const key = nextStateKeys[i]; | |
if (nextState[key] !== this.state[key]) { | |
console.warn(`[MyComponent]: nextState.${key} is not equal to the current value. This causes re-render`) | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Motivation
This snippet allows you to precisely define what is causing a re-render of your
PureComponent
.Real live example. You have a list of "List Item"'s. You call a
render
on the list. You are confident that only one specific "List Item" should be re-rendered. But for some reason, you see that other components are re-rendered(easy to see those re-renders using react-devtools). Okay, but why other items are updated?How to use?
React.PureComponent
but fromReact.Component
;shouldComponentUpdate
from a snipper to "List Item";props
forcing a not unexpected render.