I'm currently using Mobx-State-Tree
to manage all of the state for a form in my React application. The issue I'm facing is that I want to create the store at the page level, following atomic design, of the form and pass the store down to the necessary components via React Context, but I want to avoid wrapping my child component in <Observer>
tags from Mobx-react
, or having some kind of custom wrapper on my child that consumes the store and passes it in as a prop to the child.
There must be a best practice around this? The Mobx-react
documentation states:
"It is possible to read the stores provided by Provider
using React.useContext
, by using the MobXProviderContext
context that can be imported from mobx-react
."
But then I'm unable to find any examples or explanation of how best to implement MobXProviderContext
? My current setup is as follows (hugely simplified to demonstrate the situation):
import { types } from "mobx-state-tree";
const ExampleContext = React.createContext("default");
const exampleStore = types.model({ prop: types.optional(types.string, "") }).create();
const ChildComponent = () => (
<ExampleContext.Consumer>
{example => <Observer>{() => <div>{example.prop}</div>}</Observer>}
</ExampleContext.Consumer>
);
const ParentComponent = () => (
<ExampleContext.Provider value={exampleStore}>
<ChildComponent />
</ExampleContext.Provider>
);
Ultimately I'm interested in how to avoid the nesting on the child component? How should I be constructing the child component? The situation I'm applying this to is the state management of a form so the store data is constantly being updated, so it is crucial that the child is observing any updates to the values in the store.
Hope that makes sense and really appreciate any guidance on how best to approach this!