React + MobX Crash Course
Originally posted on Twitter as a thread: https://twitter.com/hexrcs/status/1201593792417144833
State management in React apps can be a hard thing to do. Are you having a hard time
wrapping your head around React state management, and getting tired of writing
boilerplate for Redux? Let's check out MobX - everything becomes so simple and
effortless
1 - MobX Concepts
MobX is a "reactive" state management library.
We directly mutate the state. Because we use MobX to observe and track mutations, the
UI will be auto-updated, like cell updates in Excel. Network requests can also auto-send
when conditions are met.
Everything is automatic!
2 - Decorator and observable
We normally use the decorator syntax to mark fields in a class "MobX observables" - easy
to use or read. This way, normal JS stuff gets "enhanced" (eg. a JS number becomes an
observable that can be tracked).
Grouping state logic in a "store" also makes our code more modular.
3. Action and Computed
In addition to @observable, we also have:
• @computed - derived state from other observable/computed that can be used
just like observables. Getter syntax is required. The derivation is automatic.
• @action - batched state mutations. Reactions will only be triggered by the
update when the action completes.
4. Reactions
We can use autorun() or when() to watch observables and perform effects when there's
update:
• autorun() takes a callback and runs it each time any observable used in it gets
updated. (Remember to do the clean-up!)
• when() only runs the callback once, when a condition is met.
5. Using MobX with React
mobx-react binding lets us use MobX with React without writing autorun functions to
rerender components.
We use @observer as a decorator to a class component, or HoC wrapping a function
component. This creates an observer component that tracks observables needed during
render, and auto rerenders whenever an update is observed.