Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why Provider component and context needed? #719

Closed
alisabzevari opened this issue Jun 12, 2017 · 5 comments
Closed

Why Provider component and context needed? #719

alisabzevari opened this issue Jun 12, 2017 · 5 comments

Comments

@alisabzevari
Copy link

As I understood from the source code of Provider and connect, Provider acts as a dependency container that holds the store and makes it available for the connect. My question is, why it should be a component and why it should use React's context at all?

Wouldn't it be possible to just define a module that holds the created store as a local variable in the module?

@markerikson
Copy link
Contributor

Yes, it would be possible to explicitly import the store everywhere, but that makes testing and SSR much more difficult. See http://redux.js.org/docs/faq/StoreSetup.html#store-setup-multiple-stores .

Since Provider and connect act as a lightweight Dependency Injection mechanism, that allows your "plain" components to be ignorant of the fact that they're getting data from Redux, and thus makes testing easier.

@alisabzevari
Copy link
Author

I think you misunderstood my question. I am asking why connect's implementation uses context to access the store. It could just import a module and get the store from that instead of polluting the context. Here is simplified implementation of my thoughts:

// provider.js (in react-redux package - Hypothetically)
let store;

const registerStore = (store) => store = store;

const getStore = () => store;

export { registerStore, getStore };

// connect.js (in react-redux package - Hypothetically)

import { getStore } from './provider';

// same connect code but just use getStore to access to the store.

// index.js

import { createStore } from 'redux';
import { registerStore } from 'react-redux';

const store = createStore(rootReduer, enhancer);
registerStore(store);
...

@jimbolla
Copy link
Contributor

Singletons, especially stateful ones, are usually an antipattern. This especially would be bad for server-side.

@markerikson
Copy link
Contributor

Yep - the linked FAQ entry discusses this.

@alisabzevari
Copy link
Author

Thanks for your answers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants