What does the autorun() function do?
What autorun() is
autorun() is a MobX function that automatically runs the function passed to it and reruns it whenever any observable data used inside that function changes.
In short:
autorun() = "a reactive observer". MobX itself determines which data your function depends on and reruns it when that data changes.
1. Example of the simplest use
import { observable, autorun } from "mobx"
const counter = observable({
count: 0,
})
autorun(() => {
console.log("Counter changed:", counter.count)
})
counter.count++ // → "Counter changed: 1"
counter.count++ // → "Counter changed: 2"What happened:
- autorun() called the passed function once on startup;
- MobX analyzed that counter.count is used inside it;
- the function reruns every time count changes.
2. How it works under the hood
- MobX runs the function once.
- It tracks all the observables that were used during that run.
- When any of them changes, MobX calls the function again.
This way, autorun() builds the dependency graph automatically, unlike reaction(), where you explicitly specify what to watch.
3. Difference between autorun() and reaction()
| Feature | autorun() | reaction() |
|---|---|---|
| What it tracks | Everything used inside the function | Only the result of the selector function |
| When it's called | Immediately on creation | Only on the first change |
| What it does | Runs side effects (logging, API, localStorage) | Runs controlled reactions |
| When it reruns | On any dependency change | Only if the tracked value actually changed |
| Control over dependencies | Automatic | Manual |
In simple terms:
- autorun = "watch everything I use inside"
- reaction = "watch a specific expression"
4. Example: logging state
import { makeAutoObservable, autorun } from "mobx"
class CartStore {
items = []
constructor() {
makeAutoObservable(this)
autorun(() => {
console.log("Number of items:", this.items.length)
})
}
add(item) {
this.items.push(item)
}
}
const cart = new CartStore()
cart.add("T-shirt") // → Number of items: 1
cart.add("Jeans") // → Number of items: 2MobX tracks that this.items.length is used inside the function and will automatically call autorun() when the array changes.
5. Example: saving state to localStorage
autorun(() => {
localStorage.setItem("settings", JSON.stringify(store.settings))
})Every time store.settings changes, MobX re-saves the data.
6. Example: a reactive side effect with computed
import { makeAutoObservable, autorun } from "mobx"
class Temperature {
celsius = 25
constructor() {
makeAutoObservable(this)
autorun(() => {
console.log(`Temperature in F: ${this.fahrenheit}`)
})
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32
}
}
const temp = new Temperature()
temp.celsius = 30 // → Temperature in F: 86MobX tracks that fahrenheit depends on celsius and calls autorun() every time the temperature changes.
7. Features of autorun()
- Always runs once right after it's declared.
- Automatically subscribes to all dependencies used inside the function.
- Returns a dispose() function to stop the observation.
Example of stopping it
const stop = autorun(() => {
console.log(store.count)
})
store.count++ // works
stop() // disable
store.count++ // nothing happens8. When to use autorun()
Ideal for side effects:
- logging, analytics, tracking
- syncing state with localStorage / URL / API
- integrating MobX with external libraries (not React)
But not recommended for:
- computations (use computed),
- UI logic (use observer).
9. Difference from computed
| computed | autorun | |
|---|---|---|
| What it does | Computes a value | Triggers a side effect |
| Cached | Yes | No |
| Returns | A new value | Nothing |
| Dependencies | Automatic | Automatic |
| Changes state | No | Can |
10. Visually
[observable] → [autorun()] → [side effect]Example: store.count -> autorun() -> console.log('Count:', count)
SUMMARY
autorun() is an automatic observer that runs the function on initialization and on every change to any observable data used inside it.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.