How to detect rerenders in React JS correctly?
Asked Answered
T

1

8

Let's say we have a parent component and multiple functional child components. I want to clearly know if the parent re-renders does the child re-renders or not.

After going through a few articles I came to know there are 3 ways we can detect rerenders. (Let me know if there are more ways.)

1. Put a console.log in the child component.

2. Use Chrome paint flashing option in the settings.

enter image description here

3. Use React dev tool

enter image description here

Do all these ways are correct to know if the component really rerenders? Because it doesn't seem to be work correctly with React.memo.

When I am wrapping the Child component with React.memo it does not print console.log, when the parent component rerenders which is correct. But still with chrome and react dev tools highlights the child component as if it rerendered.

CodeSandbox: https://codesandbox.io/s/bold-cloud-iv0rv (If we add a new car still the static component is highlighted in green, but as per Memo, it should not rerender.)

Now my doubt, Is paint flashing does not work correctly or React.memo having issues?

Testis answered 25/2, 2020 at 5:45 Comment(3)
are you sure am able to see a log being printed in your sandbox console...Decahedron
@pavankumar, For first render it will print for sure, but if the component wrapped with React.memo , it does not print console.log for subsequent renders when the Add button is clicked.Testis
Related & helpful - Trace why a React component is re-renderingPicked
T
4

Reason

If you use React.memo, you need to use it from parent down to all the child till the end.

Since React.PureComponent share the same feature with React.memo, you can find those explanation in the document as below.

Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.

Result

By changing parent component Cars to memo

// Before
export default Cars;
// After
export default React.memo(Cars);

You could find the react-dev-tools in chrome will only show the parent component re-rendered this time as well as no child console.log fired, which is correct. (Compare to previous, all the child also got highlighted)

Before enter image description here

After enter image description here

Conclusion

Both console.log and react-dev-tools worked well, you may just need to implement in a proper way following your demand.

Trant answered 25/2, 2020 at 6:48 Comment(1)
you need to use it from parent down to all the child till the end. was the most important concept that I missed. Thanks a lot for the detailed explanation. Indeed it helped me to get a clear picture how to use memo.Testis

© 2022 - 2024 — McMap. All rights reserved.