Reputation: 2868
I want to use connect
for its performance optimizations and ease of use with mapStateToProps
. I don't think I need to pass the store to the component from a <Provider>
wrapper component to any child components, because I don't have any child components that will need the store; I want the store to be in one component, which is "Header.jsx". Mainly, I don't have any other components, other than the default React, and Material-UI, ones, that I want to use the store with.
How would I go about it? I tried to pass the store through defaultProps
and used export default connect(mapStateToProps)(Header)
but it keeps saying Uncaught Invariant Violation: Could not find "store" in the context of "Connect(Header)".
I read that context is what's used to get props passed down the tree using the provider.
I'm new to Redux and React so if I'm going about this completely the wrong way, please let me know.
If using connect
can't be done without a provider, how would I go about wrapping my class from the inside?
Example:
class componentName extends Component {
constructor(props) {
super(props);
};
render() {
return (
<h1>Hello World!</h1>
);
}
}
export default connect(mapStateToProps)(<Provider store={storeName}>componentName</Provider>); // Maybe something like this?
Upvotes: 5
Views: 2727
Reputation: 1893
I think you simply cannot use connect()
without the <Provider/>
- it depends on that pattern being followed. If you want to use connect()
, the connected component must be a descendant of the provider. The example you have suggested of including the <Provider/>
in the call to connect()
will not work, as:
a) That method takes a react component class, not an already instantiated react element, and b) Even then, it creates a component class that, upon being instantiated/mounted, checks the context for a store, and this happens both above (in terms of DOM-hierarchy) the Provider that would create the context and before it is mounted and has a chance to create that context.
What's the reason you are against using the <Provider/>
? Are you trying to prematurely optimize because you think including the provider at the root of your app will have some performance impact? If so, I think you may find there is no appreciable impact from including it, or if you are experiencing one, I would suggest that the problem may be in the setup of your reducers, not simply in the use of <Provider/>
.
If you are absolutely set on not using the reducer, you could take your Store
object (returned from wherever you are calling createStore()
), and, in the componentDidMount()
of your one component that needs it you could store.subscribe()
to listen to state changes, then use store.getState()
to get those changes and load them into state. But eventually, you'll find you are just reimplementing <Provider/>
, although maybe without the context part.
TL;DR: Sounds like an XY problem
Upvotes: 5