Why connect
wrap Component using ContextToUse.Provider
instead of Consumer
?
#1875
-
In the source code here: const renderedChild = useMemo(() => {
if (shouldHandleStateChanges) {
// If this component is subscribed to store updates, we need to pass its own
// subscription instance down to our descendants. That means rendering the same
// Context instance, and putting a different value into the context.
return (
<ContextToUse.Provider value={overriddenContextValue}>
{renderedWrappedComponent}
</ContextToUse.Provider>
)
}
return renderedWrappedComponent
}, [ContextToUse, renderedWrappedComponent, overriddenContextValue]) And in the Provider.tsx here, we can know that react-redux using Context API to combine the react component and redux stores. If store data changed, Consumer will recevie the new props. But why |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Because each connected component should only re-render when its nearest connected ancestor component has rendered. This is necessary to ensure that |
Beta Was this translation helpful? Give feedback.
Because each connected component should only re-render when its nearest connected ancestor component has rendered. This is necessary to ensure that
mapState
always has access to the latest props from the immediate parent component. To do that,connect
triggers a cascade of additional "update" notifications. The only way for this to work is to override thesubscription
field in the context value object, and doing that requires re-rendering the sameContext.Provider
component with an updated value.