Why do I need to use Context or a Provider with MobX? Why do I need to use Context or a Provider with MobX? reactjs reactjs

Why do I need to use Context or a Provider with MobX?


I was interested in this question some time ago. And answer that I've got from the maintainers is because of the testability of the code.

With the code in your example you are basically treating TheTimer class as a singleton.

If you really dislike using React.context you could also use the service locator pattern instead (but basically it's the same thing)

export const ListHolder = observer(function(props) {  const listStore = serviceLocator.get(STORES.LIST_STORE)  return (    <div>      <div className={styles.wrap}>        {listStore.lists.map(list => {          return <List key={list.id} list={list} />        })}      </div>    </div>  )})

Also take a look at this long but interesting discussion on the MobX repo about exactly this problem.

suggested best practice for holding onto a store constructed with props


Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

Provider allows consuming components to subscribe to context changes.

In Mobx we use providers in the top level to pass all store instances to all the child components that are wrapped with Provider eg

import { Provider } from "mobx-react";<Provider {...Stores}>   <App/> </Provider>

Now we can access all the store properties inside the child component as props by using the inject Hoc eg

class App extends Component {  render() {    return <div>app</div>;  }}export default inject("app")(App);

You can also inject multiple stores using inject Hoc to access property stored in multiple store

inject(stores => ({ abc: stores.abc, bca: stores.bca}))

So it will resolve the problem of importing the store directly inside component which is also not recommended by mobx