Defining the Provider component

We could now initialize the store in our App component, and pass it down to all of the other components. However, it is a better idea to use React Context. That way, we can access the store from anywhere in our app. MobX React offers a Provider component, which provides the store in a context.

Let's get started using the Provider component now:

  1. Edit src/index.js, and import the Provider component from mobx-react:
import { Provider } from 'mobx-react'
  1. Then, import the TodoStore from our store.js file:
import TodoStore from './store'
  1. Now, we create a new instance of the TodoStore class:
const store = new TodoStore()
  1. Finally, we have to adjust the first argument to ReactDOM.render(), in order to wrap the App component with the Provider component:
ReactDOM.render(
<Provider todoStore={store}>
<App />
</Provider>,
document.getElementById('root')
)
Unlike Redux, with MobX, it is possible to provide multiple stores in our app. However, here, we only provide one store, and we call it todoStore.

Now, our store is initialized and ready to be used in all other components.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.27.244