React count the number of renders for an individual component

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!

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.

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!


2 Replies

Leave a Reply

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

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X