Defining a store Hook

First of all, we have to define a Hook in order to access our own store. As we have learned before, MobX uses React Context to provide, and inject, state into various components. We can get the MobXProviderContext from mobx-react and create our own custom context Hook in order to access all stores. Then, we can create another Hook, to specifically access our TodoStore.

So, let's begin defining a store Hook:

  1. Create a new src/hooks.js file.
  2. Import the useContext Hook from react, and the MobXProviderContext from mobx-react:
import { useContext } from 'react'
import { MobXProviderContext } from 'mobx-react'
  1. Now, we define and export a useStores Hook, which returns a Context Hook for the MobXProviderContext:
export function useStores () {
return useContext(MobXProviderContext)
}
  1. Finally, we define a useTodoStore Hook, which gets the todoStore from our previous Hook, and then returns it:
export function useTodoStore () {
const { todoStore } = useStores()
return todoStore
}

Now, we have a general Hook, to access all stores from MobX, and a specific Hook to access the TodoStore. If we need to, we can also define more Hooks for other stores at a later point.

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

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