Skip to content

Instantly share code, notes, and snippets.

@fedyk
Last active March 26, 2019 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedyk/f9ded4d385dcd289a3c2954ee746edef to your computer and use it in GitHub Desktop.
Save fedyk/f9ded4d385dcd289a3c2954ee746edef to your computer and use it in GitHub Desktop.
Why my `PureComponent` is re-rendered?
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;
}
@fedyk
Copy link
Author

fedyk commented Mar 22, 2019

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?

  1. Change the "List Item" component extending from React.PureComponent but from React.Component;
  2. Add a method shouldComponentUpdate from a snipper to "List Item";
  3. Do your test scenario that causing re-render;
  4. Check out the log's warnings. You should see what props forcing a not unexpected render.
  5. Fix the problematic props and enjoy responsive UI

The example of log's warnings:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment