Chris D
Chris D

Reputation: 225

React check how many times a component re-renders

I'm working on something and a piece of my code is a bit slow, what I think happens is that the component re-render too many times for no reason. Is there any way to check how many times a component re-renders in react(or react-native for the matter)? What i've tried to do is put a console.log after the render method and count how many there are but i'm not sure if that would work. Thanks in advance!

Upvotes: 19

Views: 37136

Answers (4)

vojda
vojda

Reputation: 1

the easiest way to count renders is to use console.log like this:

let counter = 0;

const Component = () => {
    
console.log('counting re-renders', (counter += 1));
    
    return (
     <> 
     </>
   ) 
}

Upvotes: 0

Sifat Haque
Sifat Haque

Reputation: 6057

you can place console.count('counter') in your render function to check this. Here you'll find all the details about console.count link

Upvotes: 19

Konrad Dziurdź
Konrad Dziurdź

Reputation: 777

Better than putting console.log in every component is to use this small util

https://github.com/maicki/why-did-you-update

You will be warned in console every time component re-rendered needlessly (e.g. props nor state did change)

Even though it's not maintained anymore it works perfectly.

Best regards

Upvotes: 7

Katia Wheeler
Katia Wheeler

Reputation: 549

console.log will work, if you place it within your render function. If you're concerned about a component re-rendering too many times, try extending React.PureComponent. Info about PureComponent can be found in React's docs. You could also look into the shouldComponentUpdate method to see if that will help solve your re-rendering. Info about that is also in their docs. Good luck!

Upvotes: 10

Related Questions