Skip to main content

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

javascript
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

  1. MobX runs the function once.
  2. It tracks all the observables that were used during that run.
  3. 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()

Featureautorun()reaction()
What it tracksEverything used inside the functionOnly the result of the selector function
When it's calledImmediately on creationOnly on the first change
What it doesRuns side effects (logging, API, localStorage)Runs controlled reactions
When it rerunsOn any dependency changeOnly if the tracked value actually changed
Control over dependenciesAutomaticManual

In simple terms:

  • autorun = "watch everything I use inside"
  • reaction = "watch a specific expression"

4. Example: logging state

javascript
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: 2

MobX 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

javascript
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

javascript
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: 86

MobX 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

javascript
const stop = autorun(() => { console.log(store.count) }) store.count++ // works stop() // disable store.count++ // nothing happens

8. 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

computedautorun
What it doesComputes a valueTriggers a side effect
CachedYesNo
ReturnsA new valueNothing
DependenciesAutomaticAutomatic
Changes stateNoCan

10. Visually

javascript
[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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.