can you please explain to me why I need to wrap my app in the Store Provider when using mobx with React Context. What I mean:
// Create Counter Store
class CounterStore {
constructor() {
makeAutoObservable(this)
this.num = 0
}
inc() { this.num++ }
}
// Create React Context with store
const StoreContext = React.createContext(new CounterStore())
// Create hook for usage context
const useStore = () => React.useContext(StoreContext)
// Create component
const Counter = observer(() => {
const counterStore = useStore()
return (
<>
<div>{counterStore.num}</div>
<button onClick={() => counterStore.inc()}>
inc num
</button>
</>
)
})
// Create App component
const App = () => {
return (
<Counter />
)
}
Ok everything is working fine, I have access to the store inside my counter component.
But still i didnt wrap my app into store provider like:
/// same code as above with little change
// Now create context with no value:
const StoreContext = React.createContext()
// And create Provider with store.
const StoreProvider = ({children}) => {
return <StoreContext.Provider value={new CounterStore()}>
{children}
</StoreContext.Provider>
}
Then wrap App component with provider:
render(
<StoreProvider>
<App />
</StoreProvider>,
document.getElementById("root")
);
This code works too. But i cant understand why i need to create SroreProvider and wrap my App with it, if all works fine without it