Skip to content

Instantly share code, notes, and snippets.

@CezaryDanielNowak
Created March 16, 2023 14:29
Show Gist options
  • Save CezaryDanielNowak/a943d7a6b32402e3edc06a7dd652185c to your computer and use it in GitHub Desktop.
Save CezaryDanielNowak/a943d7a6b32402e3edc06a7dd652185c to your computer and use it in GitHub Desktop.
/**
* How to use:
* In the render function, include
*
* window.whyRerender && window.whyRerender(this.props, this.state);
*/
window.whyRerender = (props, state) => {
if (window.whyRerender.prevProps) {
const propsDiff = Object.keys(props).map((propName) => {
if (props[propName] !== window.whyRerender.prevProps[propName]) {
return propName;
}
}).filter(Boolean);
const stateDiff = Object.keys(state).map((stateName) => {
if (state[stateName] !== window.whyRerender.prevState[stateName]) {
return stateName;
}
}).filter(Boolean);
console.log('[whyRerender]', propsDiff, stateDiff)
}
window.whyRerender.prevProps = { ...props };
window.whyRerender.prevState = { ...state };
}
@CezaryDanielNowak
Copy link
Author

CezaryDanielNowak commented Mar 16, 2023

    const whyRerender = (_props, _state, name = '[whyRerender]') => {
      if (whyRerender.prevProps) {
        const propsDiff = Object.keys(_props).map((propName) => {
          if (_props[propName] !== whyRerender.prevProps[propName]) {
            return propName;
          }
        }).filter(Boolean);

        const stateDiff = Object.keys(_state).map((stateName) => {
          if (_state[stateName] !== whyRerender.prevState[stateName]) {
            return stateName;
          }
        }).filter(Boolean);

        console.log(name, propsDiff, stateDiff)
      }

      whyRerender.prevProps = { ..._props };
      whyRerender.prevState = { ..._state };
    };

...
whyRerender(this.props, this.state, this.className);

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