0

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.
jhanschoo
  • 1,236
  • 13
  • 15
  • Did you try making examples and check it? – Dennis Vash Sep 07 '19 at 13:06
  • @DennisVash I'm not very familiar with `connect`'s possible optimizations to React's re-render behavior. I wouldn't know if I can trust my results if I were to make my own examples or if I were missing/failing to distinguish an optimization scenario with them. – jhanschoo Sep 07 '19 at 16:05

1 Answers1

6

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.)

markerikson
  • 63,178
  • 10
  • 141
  • 157