I'm brand new to Redux and I'm trying to figure out the relationship between <Provider> and connect().
As I understand it, connect connects your component to the store. However, nowhere in the function arguments do you tell connect where exactly that store is!
If I'm not mistaken, the store is automagically provided to connect() by the <Provider>. This to me seems very counter-intuitive, because the entire point of Redux is to be transparent.
So my question is, how does <Provider> pass the store off to connect() without using some sort of global variable? Does it traverse the entire tree, searching for connected components and then inject itself? Is that not inefficient? And if so, how would I use two different stores within the same component tree?
Secondly, supposing I don't want to use <Provider>, how can I use connect() without it? i.e., how can I explicitly pass a store to each connected component?
<Provider> and connect are part of the react-redux module. They work together, you shouldn't really use one without the other. You can use redux on its own without react-redux, but you'll probably end up re-creating some or all of the features that react-redux provides.
react-redux works by using the React context. Context is like a hidden layer for passing variables that are shared by multiple components without explicitly passing them. To use context, you need to set the context somewhere, but also, any component that wants to use something from the context needs to get the variable. In react-redux <Provider> essentially saves the store to the context and connect provides a way to get the store from the context.
If you haven't already, I recommend these videos for getting started with Redux and react-redux from the creator of Redux.
The redux docs are pretty great and have some information regarding Provider and connect()
The option we recommend is to use a special React Redux component called
<Provider>to magically make the store available to all container components in the application without passing it explicitly. You only need to use it once when you render the root component
Essentially it leverages the use of context which is from React. As per the docs this allows you to pass data through the component tree without having to pass the props down manually at every level.
There's no reason why you can't explicitly pass the store. The idea here is that it just makes things easier.