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 😃
👇 Here's a 5-minute React + MobX crash course for you! 🥳
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!
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.
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.
We can use
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.
mobx-react binding lets us use MobX with React without writing
autorun functions to rerender components.
@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.
And that's it, everything you need to start using MobX effectively. Pretty effortless, isn't it? 😃
If you are curious how MobX works under the hood, check out this amazing talk "Reinventing MobX" by Max Gallo.
Thank you so much Michel Weststrate for creating this amazing library, and helping to review this crash course! 🙌
(Thread crash course format inspired by Chris Achard 😁 Check out his excellent React/Redux, Git crash courses!)
While you are still here, if you've got 13 more minutes and are interested in learning the new hot framework Svelte, I've also got a crash course with companion videos here 👉 Svelte Crash Course 🔥
I've also got another GraphQL Crash Course 🔥 👈 Check it out!
Like this post?