I'm preparing for senior React Native interviews, and one kind of task keeps showing up: "write your own state manager". Redux is the usual target. I picked MobX instead, because I've used it for years and realized I couldn't explain what happens between store.count++ and the re-render.
The finished version is about 150 lines: observable , autorun , computed , action , and a React hook. Getting there took a lot more than 150 lines of wrong code. This post goes through the bugs in the order I made them. Every output below comes from running the code.
The core: track on read, trigger on write
MobX doesn't ask you to declare dependencies. A reaction runs once, MobX watches which fields it reads, and from then on it reruns only when one of those fields changes.
You need two pieces for that.β¦