Suggest an editImprove this articleRefine the answer for “What does the autorun() function do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**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. **Key point:** MobX itself determines which data your function depends on and reruns it when that data changes.Shown above the full answer for quick recall.Answer (EN)Image## 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() | 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 ```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 | | 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 ```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.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.