This post assumes familiarity with MobX.
Hooks have drastically changed the way we can write functional components in React.
This proposal has brought a huge change in a way we would write functional components. Combining this with a state management lib like MobX, it is too easy to manage you app state and never write a class component ever again.
For React, we get official bindings via the mobx-react
package. But for hooks, we need to use another library mobx-react-lite. This gives us custom hooks with which we can create observables directly in our components.
A simple example is shown below:
Here, the hook useObservable
gives us a new way of creating observables, actions and computed properties all in one object. The required values can be accessed on this object and the component reacts to changes via the observer
wrapper.
Now you might be wondering, what if I have state that needs to be shared across components? mobx-react-lite
doesn't include a Provider
but we don't need it anymore as React already has that pattern... Context!
Context is the way we can share state across multiple components without techniques like lifting state up or prop-drilling. React now provides a hook called useContext
that can help us share our MobX store across multiple components.
Here is the same example featuring the classic MobX store defined as a class and being used via context.
If you view the TodoStore.js
file, you can see that it is how you would normally define a MobX store. A context is created out of an instance of this store and this now can be shared across multiple components. Easy!
I will write a follow-up post on how to test these components. Thanks for reading!
Great article, just learned about 'useReducer' i think observable will be my next hook to learn.