How does the behavior of a child component using `react-redux` change when its parent rerenders?

混江龙づ霸主 提交于 2020-03-05 06:07:31

问题


At react-redux's hooks documentation we are warned that useSelector "does not prevent the component from re-rendering due to its parent re-rendering, even if the component's props did not change," unlike connect

This is news to me. Does connect prevent re-rendering where a normal child component would not re-render? More specifically, I'm asking about the difference in the re-rendering behavior of the below three scenarios when the parent component re-renders while the store and props remain unchanged:

  1. The child component is wrapped in a connect HOC.
  2. Behavior as 1., but injected state is refactored into useSelector.
  3. As 2., but useSelector and everything dependent on it is removed.

回答1:


connect has always acted like a more sophisticated version of React's PureComponent. Specifically, when the parent of a connected component renders, connect will only re-render the child component if the new "merged props" have changed from before, where const mergeProps = { ...ownProps, ...stateProps, ...dispatchProps }.

So, if a parent component is passing down the same props as before, the connect wrapper will prevent the wrapped component from re-rendering.

With the hooks, there is no wrapper component preventing this component from re-rendering if its parent is passing down the same props. You would need to wrap your component in React.memo() to achieve that. And, in fact, that is exactly how connect itself is implemented in version 7.

(Source: I'm a Redux maintainer and wrote React-Redux v7.)



来源:https://stackoverflow.com/questions/57833717/how-does-the-behavior-of-a-child-component-using-react-redux-change-when-its-p

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