Skip to main content

useWhyDidYouUpdate

Description#

This hook makes it easy to see which prop changes are causing a component to re-render.

Usage#

If a function is particularly expensive to run and you know it renders the same results given the same props you can use the React.memo higher order component, as we've done with the Counter component in the below example.
In this case if you're still seeing re-renders that seem unnecessary you can drop in the useWhyDidYouUpdate hook and check your console to see which props changed between renders and view their previous/current values.

import { memo } from 'react';import { useWhyDidYouUpdate } from '@springtree/eva-suite-react-hooks';
const Counter = memo((props) => {  useWhyDidYouUpdate('Counter', props);
  return (    <div style={props.style}>      {props.count}    </div>  );});
const Example = () => {  const [count, setCount] = React.useState<number>(0);  const [userId, setUserId] = React.useState<number>(0);
  // Our console output tells use that the style prop for `Counter`  // changes on every render, even when we only change `userId` state by   // clicking the "switch user" button. Oh of course! That's because the  // `counterStyle` object is being re-created on every render.  // Thanks to our hook we figured this out and realized we should probably   // move this object outside of the component body.  const counterStyle = {    fontSize: '3rem',    color: 'red',  };
  return (    <div>      <div className="counter">        <Counter count={count} style={counterStyle} />        <button onClick={() => setCount(count + 1)}>Increment</button>      </div>      <div className="user">        <img src={`http://i.pravatar.cc/80?img=${userId}`} />        <button onClick={() => setUserId(userId + 1)}>Switch User</button>      </div>    </div>  );};
export default Example;

References#