Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - How to detect rerenders in React JS correctly?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...