How to detect rerenders in React JS correctly?

核能气质少年 提交于 2021-02-05 10:38:40

问题


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.

3. Use React dev tool

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?


回答1:


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

After

Conclusion

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



来源:https://stackoverflow.com/questions/60388198/how-to-detect-rerenders-in-react-js-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!