React createContext with defult value for use Mobx store

384 Views Asked by At

i am creating a context to use Mobx store in my React application, by following the example:

 const mainStore = new MainStore(); // mobx store instance
    const storeContext = React.createContext(mainStore);
    export const useStores = () => React.useContext<typeof mainStore>(storeContext);
    
    ReactDOM.render(
      <React.StrictMode>
        <storeContext.Provider value={{...mainStore}}>
          <NavigationProvider>
            <Router>
              <App />
            </Router>
          </NavigationProvider>
        </storeContext.Provider>
      </React.StrictMode>,
      document.getElementById('root'),
    );

and in components is used by example:

    function App() {
        const { authStore } = useStores();
        const history = useHistory();
      return (<>test{authStore.isLogin}</>)
    }

and there are two questions:

question 1: why use the useStores construct when I can just call React.useContext<typeof mainStore>(storeContext); in any component itself; and just export storeContext?

question 2: if, when creating a context, one value is passed to the default value, and another value is passed to the provider value, then which of them will be used by the consumer? something like this... different context values

thanks in advance!

1

There are 1 best solutions below

0
Rusty Nail On
  1. You can avoid useStores in that case. When there are more imports or the logic increases, it will make sense

  2. Value in storeContext.Provider will be used, cause you can delcare your provider in any place of your project and get default value from network for instance