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

Comments

3 participants
@alisabzevari
Copy link

alisabzevari commented Jun 12, 2017

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

This comment has been minimized.

Copy link
Contributor

markerikson commented Jun 12, 2017

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

This comment has been minimized.

Copy link
Author

alisabzevari commented Jun 12, 2017

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

This comment has been minimized.

Copy link
Contributor

jimbolla commented Jun 12, 2017

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

@markerikson

This comment has been minimized.

Copy link
Contributor

markerikson commented Jun 12, 2017

Yep - the linked FAQ entry discusses this.

@alisabzevari

This comment has been minimized.

Copy link
Author

alisabzevari commented Jun 12, 2017

Thanks for your answers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment