šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React count the number of renders for an individual component

If a React component is re-reneded in excess it can lead to performance issues. Let's see how to count the number of renders for individual React components using the useRef() hook.

We'll also see how to extract this functionality into a custom hook for easier reuse.

In order to track and count each time an individual React component is rendered we can use the useRef() hook.

const App = () => {
  const rendersNo  = useRef(0)
  const [counter, setCounter] = useState(0)

  rendersNo.current = rendersNo.current + 1
  const increase = ()=> {setCounter(c => c + 1)}

  return(<div>
      <button onClick={increase}>
          Increase counter & trigger rerender
      </button>
      <p>Counter: {counter}</p>
      <p>Rerenders: {rendersNo.current}</p>
  </div>)
}

And if we want to extract this in a separate hook we can do:

const useRenderCount = () => {
  const rendersNo = useRef(0);
  useEffect(() => {
    rendersNo.current++;
  });
  console.log("Rerenders: " + rendersNo.current)
};

// and in the App component
const App = () => {
  useRenderCount()
  //... 
}

You can see the full codepen example here.

And speaking of the number re-renders in React, keep in mind that it matters if we use primitive or object values in the state of that component.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


2 Replies

Leave a Reply

Your email address will not be published. Required fields are marked *