Simple, scalable state management.
Anything that can be derived from the application state, should be. Automatically.
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming.
Refer to official documentation for detailed usage. →
Mobx uses observables for store values. Properties, entire objects, arrays, Maps and Sets can all be made observable.
Refer to official documentation on observable state for detailed usage. →
- Make a counter store that holds a
makeAutoObservable and its cousin
makeObservable trap existing object properties and make them observable.
makeAutoObservable is like
makeObservable on steroids, as it infers all the properties by default.
- Make a root store that holds the counter store
Before starting to read data from the store, let's add some action.
An action is any piece of code that modifies the state.
- Add actions to counter store.
Firstly store must be made accessible to components. It can be done with
React.useContext. Then with a custom hook, store can be read from components.
- Make a context to hold store.
- Use its provider to make store accessible to all components.
- Components can read from store via a custom hook.
- Wrap your component with
You might consider using mobx-react-lite instead of mobx-react if you're not using class components.
Mobx State Tree provides a better structured state management and tools you need in your app. If you want to use
mobx-state-tree, you need to make some changes to the files you've created above.
mobx-state-tree provides a simpler API to create our stores and actions.
After the changes in
CounterStore we will need to update
Finally, you need to update
RootStoreProvider with the
If you didn't choose the plugin during project creation phase, you can follow the instructions below to add it.