advanced
Reactions
Run side effects when tracked observable dependencies change while avoiding hidden feedback loops.
Reactions run side effects when observables they track change: `autorun`, `reaction`, `when`. Use them for logging, syncing to localStorage, routing, or imperative APIs — not for core derivation (use computed).
import { reaction } from 'mobx';
reaction(
() => store.filter,
(filter) => analytics.track('filter_changed', { filter }),
);
`reaction` separates tracking function from effect, avoiding accidental reads during the effect phase. Guard against feedback loops where an effect mutates an observable that re-triggers the same reaction.
The trade-off is declarative side effects versus risk of feedback loops if reactions write back to tracked state.
On interviews: reaction vs useEffect in React; when MobX reactions replace effect chains.
Common pitfalls: autorun that mutates its own dependencies, missing disposal on unmount, and duplicating React effects alongside reactions without clear ownership.
Checklist:
- Reactions for side effects only.
- Prefer reaction over autorun when data/effect split helps.
- Dispose subscriptions when store/component dies.
- Avoid loops: effect should not blindly rewrite triggers.