Hi Michel,
I tweeted it earlier but it's hard to reply there. I'm also not sure where to ask this question. I'm still curious as to why importing a store in component is not a good idea. I also did some research that as much as possible, pass props to children. Use Provider+inject only when needed.
What's bad about importing a store in component? Is it because it's harder to test? Are there other factors why it's not a good idea? What are the advantage of passing down props vs import of store? Other than easier testing, are there other reasons?
I'm new to MobX and I'd like to correct my style as early as possible.
This is the code where I'm importing a store.
import React from 'react';
import { observer } from 'mobx-react';
import URLStore from './Stores/URLStore';
@observer
class URL extends React.Component {
render() {
const { getUrls } = URLStore
const o = Object.keys(getUrls).map((property, index)=> {
return (
<li key={index}><strong>{[property]}</strong>: {getUrls[property]}</li>
)
})
return(
<div>
<ul>
{o}
</ul>
</div>
)
}
}
export default URL;
but looks like below is better?
import React from 'react';
import { observer } from 'mobx-react';
@observer
class URL extends React.Component {
render() {
const { getUrls } = this.props.URLStore;
const o = Object.keys(getUrls).map((property, index)=> {
return (
<li key={index}><strong>{[property]}</strong>: {getUrls[property]}</li>
)
})
return(
<div>
<ul>
{o}
</ul>
</div>
)
}
}
export default URL;
It's probably better to import the raw urls as a property instead of passing the store itself as a property. The dumber your components are the easier they are to test and the simpler they are for you.
Pass in raw props from a container component.
Server side rendering. You have to be able to create unique store instance per request, that's not possible if you have single store instance per module loader.
In general it's bad practise to use static, import, require, globals to control (stateful) object scope. Even singletons are single only inside certain scope, which you should be able to control. That scope isn't module loader nor language runtime env.
Thank you both. Would really appreciate @urugator if you have an example gist. Thanks a lot!
An example of what exactly?
Please ignore. I'll just rewrite my code above and use the recommend way.
Most helpful comment
Server side rendering. You have to be able to create unique store instance per request, that's not possible if you have single store instance per module loader.
In general it's bad practise to use static, import, require, globals to control (stateful) object scope. Even singletons are single only inside certain scope, which you should be able to control. That scope isn't module loader nor language runtime env.