Skip to content

Instantly share code, notes, and snippets.

@keepitsimple
Last active June 4, 2020 14:02
Show Gist options
  • Save keepitsimple/0eebb5e427c857986f1c5aac6efe28d6 to your computer and use it in GitHub Desktop.
Save keepitsimple/0eebb5e427c857986f1c5aac6efe28d6 to your computer and use it in GitHub Desktop.
Trace why a React component is re-rendering

From: https://stackoverflow.com/questions/41004631/trace-why-a-react-component-is-re-rendering

If you want a short snippet without any external dependencies I find this useful

componentDidUpdate(prevProps, prevState) {
  Object.entries(this.props).forEach(([key, val]) =>
    prevProps[key] !== val && console.log(`Prop '${key}' changed`)
  );
  if (this.state) {
    Object.entries(this.state).forEach(([key, val]) =>
      prevState[key] !== val && console.log(`State '${key}' changed`)
    );
  }
}

Here is a small hook I use to trace updates to function components

function useTraceUpdate(props) {
  const prev = useRef(props);
  useEffect(() => {
    const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
      if (prev.current[k] !== v) {
        ps[k] = [prev.current[k], v];
      }
      return ps;
    }, {});
    if (Object.keys(changedProps).length > 0) {
      console.log('Changed props:', changedProps);
    }
    prev.current = props;
  });
}

// Usage
function MyComponent(props) {
  useTraceUpdate(props);
  return <div>{props.children}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment