Reactive state and signals

MobX, Valtio, signals, and why React chose differently.

Builds on Build a store.

Every store so far has asked you to do some bookkeeping. In Build a store you wrote a selector so a component would re-render only when its slice changed. Zustand and Redux ask for the same thing, and Jotai asks you to split state into atoms up front. In all of them, you tell the library what each component depends on.

There's another school of thought, older than React's hooks and very much alive: let the state watch what you read. If a component reads book.read, record that. When book.read changes, update exactly the things that read it. No selectors, no equality functions. This chapter builds that idea from scratch with a JavaScript Proxy, then runs it for real in MobX and Valtio, then looks at the purest form of it, signals, and ends with the question interviewers like: if fine-grained reactivity is so precise, why didn't React adopt it?

The problem: selectors are dependency lists you write by hand#

Here's the toy store from chapter 33 in miniature, with a component that reads two fields. The selector has to name both of them, and it has to return something that compares equal when nothing it cares about changed.

// With the toy store (or Zustand), you declare dependencies yourself.
function CartTotal() {
  const total = useStore((s) => s.price * s.qty); // deps: price, qty
  return <p>Total: {total}</p>;
}

function CartBadge() {
  // Oops: a new object on every call. Under a plain Object.is check that's a
  // "change" every time: the chapter 33 toy and Zustand 5 loop, and even with
  // a shallow equality function you had to remember to add it.
  const { qty, coupon } = useStore((s) => ({ qty: s.qty, coupon: s.coupon }));
  return <span>{qty} items {coupon && "(discount)"}</span>;
}

Two kinds of bug live here. Return a fresh object, or select more than you use, and you loop or re-render too often (the badge). Select too little, or compute something from a stale closure, and you miss updates. The selector is a dependency list, and like useEffect dependency arrays, hand-written dependency lists drift.

The function body already knows what it depends on: it's whatever it reads. If reads could be observed, the dependency list would write itself.

Build it: dependency tracking with a Proxy#

A Proxy lets you intercept property reads (get) and writes (set) on an object. That's all we need:

  1. Keep a global "who is running right now" pointer, currentReaction.
  2. On every read, if a reaction is running, record "this reaction depends on this property".
  3. On every write, re-run the reactions recorded for that property.
  4. Each time a reaction re-runs, forget its old dependencies and record them fresh, because branches can change what it reads.

That last step is easy to forget and it matters. We'll call a function that tracks its reads and re-runs on change an autorun, which is MobX's name for it.

Dependency tracking in 50 lines
import { observable, autorun } from "./reactive.js";

const cart = observable({ price: 10, qty: 2, coupon: "" });

autorun(() => console.log("total:", cart.price * cart.qty));
autorun(() => console.log("coupon:", cart.coupon || "(none)"));

console.log("--- qty = 3");
cart.qty = 3; // only the total reaction re-runs

console.log("--- coupon = SAVE10");
cart.coupon = "SAVE10"; // only the coupon reaction re-runs

console.log("--- qty = 3 again");
cart.qty = 3; // same value: nothing runs
Nothing logged yet.

Read the console. Each write re-ran exactly the reactions that read that property, and a write of the same value ran nothing. No selector told it anything. The dependency graph was discovered by running the code.

Swap "log to the console" for "re-render a component" and you have MobX's React binding. Swap it for "set the textContent of one DOM node" and you have SolidJS. Hold on to the four steps above: every library in this chapter is a production version of them.

PredictDependencies that move

Using the toy above, what does this log after the initial run, for each of the three writes?

const ui = observable({ showPrice: false, price: 10, label: "Book" });

autorun(() => {
  console.log(ui.showPrice ? `price: ${ui.price}` : `label: ${ui.label}`);
});

ui.price = 12;      // (a)
ui.showPrice = true; // (b)
ui.label = "Novel";  // (c)
Build itWrite autorun yourself

observable is done. Implement autorun(fn) in reactive.js so the checks pass. It must run fn once immediately, track what it reads, re-run when one of those properties changes, re-track on each run (dropping dependencies from branches it no longer takes), and return a function that stops it.

// A reaction is { sources: Set<Set<reaction>>, run(): void }.
// observable() adds the running reaction to a property's reader set,
// and adds that reader set to reaction.sources.
let currentReaction = null;
const deps = new WeakMap();

export function observable(obj) {
  return new Proxy(obj, {
    get(target, key, receiver) {
      if (currentReaction) {
        let byKey = deps.get(target);
        if (!byKey) deps.set(target, (byKey = new Map()));
        let readers = byKey.get(key);
        if (!readers) byKey.set(key, (readers = new Set()));
        readers.add(currentReaction);
        currentReaction.sources.add(readers);
      }
      return Reflect.get(target, key, receiver);
    },
    set(target, key, value, receiver) {
      const old = target[key];
      const ok = Reflect.set(target, key, value, receiver);
      if (!Object.is(old, value)) {
        const readers = deps.get(target)?.get(key);
        if (readers) [...readers].forEach((r) => r.run());
      }
      return ok;
    },
  });
}

export function autorun(fn) {
  // TODO: create a reaction, run it with currentReaction set,
  // and return a disposer.
  fn();
  return () => {};
}
Nothing logged yet.

MobX: observable classes and observer components#

MobX (version 7.1 in the sandbox) is the long-running, production version of what you just built. Its core API maps one to one:

ToyMobXWhat it does
observable(obj)observable(obj), makeAutoObservable(this)Wrap state so reads are tracked and writes notify.
autorun(fn)autorun(fn), reaction(...)Run side effects when what they read changes.
(not built)computed (a getter)A derived value, cached, recomputed only when its inputs change.
plain assignmentactionGroup writes into one batch so reactions run once, after all of them.
re-render instead of logobserver(Component) from mobx-react-liteTrack what a component reads during render, re-render when it changes.

makeAutoObservable(this) in a class constructor turns fields into observables, getters into computeds and methods into actions. Then wrap every component that reads observable state in observer. Toggle a book below and watch the render counters.

MobX: a reading list with observer components
import { observer } from "mobx-react-lite";
import { Rendered } from "guide-tools";
import { store } from "./store";

const Row = observer(function Row({ book }: { book: (typeof store.books)[number] }) {
  return (
    <Rendered label={`Row ${book.id}`}>
      <label>
        <input type="checkbox" checked={book.read} onChange={() => store.toggle(book.id)} /> {book.title}
      </label>
    </Rendered>
  );
});

// Reads the array and each book's id, but never book.read.
const List = observer(function List() {
  return (
    <Rendered label="List">
      {store.books.map((b) => (
        <Row key={b.id} book={b} />
      ))}
    </Rendered>
  );
});

const Counter = observer(function Counter() {
  return <Rendered label="Counter">{store.unread} unread</Rendered>;
});

export default function App() {
  return (
    <>
      <Counter />
      <List />
    </>
  );
}

Toggle a book. Only that row and the counter re-render. List doesn't, because during its render it read the array and each book's id, never read. Nobody wrote a selector, and nobody wrapped anything in memo. You'll also see "computing unread" once per toggle, not once per render: unread is a computed, cached until one of its inputs changes.

How does observer re-render a component? In mobx-react-lite 5 it runs your render function inside a MobX Reaction (the toy's reaction object, grown up) and connects that reaction to React with useSyncExternalStore: when a tracked value changes, the reaction bumps a version and notifies the subscription, and React re-renders. That's the same bridge you wrote in chapter 33. MobX supplies the "what changed" part; React still does the rendering.

Actions and async#

By default MobX runs with enforceActions: "observed": changing observed state outside an action prints a warning. Actions also batch: inside one action, reactions wait until the outermost action finishes, so three writes cause one re-render.

Async code is where people trip. Code after an await is no longer inside the action that started it:

class BooksStore {
  books: Book[] = [];
  loading = false;
  constructor() {
    makeAutoObservable(this);
  }

  async load() {
    this.loading = true; // inside the action: fine
    const data = await fakeFetch("/books");
    // This runs later, outside the action. Wrap it:
    runInAction(() => {
      this.books = data;
      this.loading = false;
    });
  }
}

MobX also offers flow (a generator-based action) for the same job. And note what you just wrote: hand-rolled loading flags for server data. Server state explains why that's usually the wrong layer for it.

Valtio: mutate a proxy, read a snapshot#

Valtio takes the same tracking idea and fits it to React's love of immutable values. You create state with proxy() and mutate it directly. Components call useSnapshot(state) and get back an immutable snapshot to render from. The rule of thumb from Valtio's own docs: read from snapshots, mutate the source.

Valtio: render-optimized snapshots
import { proxy, useSnapshot } from "valtio";
import { books, Rendered } from "guide-tools";

const state = proxy({
  books: books.slice(0, 4).map((b) => ({ ...b, read: false })),
  filter: "",
});

function toggle(id: number) {
  const book = state.books.find((b) => b.id === id); // mutate the proxy
  if (book) book.read = !book.read;
}

function Counter() {
  const snap = useSnapshot(state); // reads books[i].read, never filter
  return <Rendered label="Counter">{snap.books.filter((b) => !b.read).length} unread</Rendered>;
}

function Filter() {
  // sync: true so typing doesn't jump the caret (see Pitfalls)
  const snap = useSnapshot(state, { sync: true });
  return (
    <Rendered label="Filter">
      <input placeholder="Filter titles" value={snap.filter} onChange={(e) => (state.filter = e.target.value)} />
    </Rendered>
  );
}

function List() {
  const snap = useSnapshot(state);
  const visible = snap.books.filter((b) => b.title.toLowerCase().includes(snap.filter.toLowerCase()));
  return (
    <Rendered label="List">
      {visible.map((b) => (
        <label key={b.id} style={{ display: "block" }}>
          <input type="checkbox" checked={b.read} onChange={() => toggle(b.id)} /> {b.title}
        </label>
      ))}
    </Rendered>
  );
}

export default function App() {
  return (
    <>
      <Counter />
      <Filter />
      <List />
    </>
  );
}

Type in the filter: Counter doesn't re-render, because it never touched snap.filter. Toggle a book: Filter doesn't re-render, because it only read filter.

The mechanism is a second proxy. useSnapshot subscribes with useSyncExternalStore, and wraps the snapshot it returns in a tracking proxy (from the proxy-compare library) that records which paths your render touched. When the state changes, Valtio compares the new snapshot to the old one only along those paths. If none changed, it hands React the same snapshot and the component skips the re-render. It's an auto-generated selector.

MobX and Valtio differ more in taste than in mechanism:

  • MobX gives you mutable observable objects, often classes with computeds and actions, and an observer wrapper. It suits rich domain models and has a decade of production use.
  • Valtio keeps React's immutable-snapshot rendering model and hides the proxy behind useSnapshot. It's small and feels like plain objects.

Signals: reactivity as a primitive#

Strip the proxies away and you get the smallest reactive unit: a signal, a container for one value that tracks who reads it. Add computed (derived signals, cached) and effect (side effects that re-run), and you have the whole model. This is the toy above, one value at a time instead of one property at a time.

Most non-React frameworks have converged on it. The shapes differ, the idea doesn't:

Preact Signals
import { signal, computed, effect } from "@preact/signals";

const qty = signal(2);
const price = signal(10);
const total = computed(() => qty.value * price.value);

effect(() => console.log("total", total.value)); // logs 20
qty.value = 3; // logs 30

// In a Preact component, rendering {total} (the signal itself, not .value)
// binds it straight to a text node: updates skip the component entirely.

The key difference from React is visible in the Solid example: the component function runs once. It's setup code, not a render function. Updates never re-run it. The compiler turns {total()} into a tiny effect bound to one text node, so a change goes from signal to DOM node directly. No virtual DOM, no diff. That's what "fine-grained reactivity" means.

The TC39 Signals proposal, championed by people from Angular, Ember, Preact, Solid, Svelte, Vue and others, aims to standardize the core graph (state, computed, and a low-level watcher) so frameworks could share one implementation and reactive libraries could work across frameworks. It reached Stage 1 in April 2024 and, as of November 2026, is still at Stage 1 on TC39's proposal list. Stage 1 means the committee agrees the problem is worth exploring; the API can change completely, and nothing ships in engines. Don't describe it as "coming to JavaScript" in an interview; describe it as an exploration.

Dependency tracking versus re-render and diff
Fine-grained (signals, MobX)price = 10qty = 2total = 20DOM text "Total: 20"the only readerEdges are recorded while values are read.ReactsetQty(3)Cart() runs againand its non-memoized childrendiff new tree against old treepatch text to "Total: 30"Work found by re-running and comparing.
Step 1 of 5

The same cart total, built two ways. Left: a fine-grained graph (signals, MobX). Right: React's model. Both start showing Total: 20.

Why React chose a different model#

React knows about signals. The team has explained its choice many times, and the reasons are design trade-offs, not ignorance. Be fair about both sides.

What signals genuinely do better. Updates cost work proportional to what changed, not to the size of the component that owns the state. There's no diffing, no memo, no dependency arrays, no selector discipline. A dashboard with thousands of independently ticking cells is the textbook win.

Why React stays with re-render and diff:

  1. UI as a pure function of state. A React component is a function from plain values to a description of UI. Inside it you use ordinary JavaScript: map, filter, early returns, local variables, any helper. Values are values. With signals, values become containers you have to read in the right place (count() inside the tracked scope, not destructured outside it), and the reactive boundary is something you must keep in your head. React chose a simpler mental model and accepted extra work at runtime.

  2. Coarse re-rendering is cheaper than it sounds, and the Compiler narrows it. Re-running a component is usually fast; the expensive cases are large subtrees and costly calculations. That's exactly what memoization removes, and the React Compiler now inserts that memoization automatically, so unchanged JSX and derived values are reused without you writing memo or useMemo. The gap to fine-grained updates gets much smaller, while the programming model stays "just functions".

  3. Concurrent rendering needs consistent snapshots. React can render an update in the background (a transition), pause it, throw it away, or show the old UI while the new one prepares. That works because a render reads immutable values: the whole tree renders against one consistent version of the state. Mutable reactive values that push updates synchronously don't fit that model. This is the tearing problem again, and it's why MobX, Valtio and every external store connect through useSyncExternalStore, which keeps the tree consistent by treating store updates as blocking: if a store changes during a non-blocking transition, React falls back to a synchronous render for it.

  4. One model on server and client. Server Components and SSR render a tree from data once. "A function of state" carries across that boundary naturally.

The honest summary: signals optimize the update path; React optimizes the programming model and concurrency, then wins back performance with the scheduler and the Compiler. Both are defensible. In a React app you can still use signal-like libraries (MobX and Valtio are exactly that), but they plug into React's rendering, they don't replace it.

Pitfalls#

Check your understanding#

Fix itThe counter that never moves

Checking a book should update the unread count. The store is fine. The UI isn't. Fix it.

import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react-lite";
import { books } from "guide-tools";

class Store {
  books = books.slice(0, 3).map((b) => ({ ...b, read: false }));
  constructor() {
    makeAutoObservable(this);
  }
  get unread() {
    return this.books.filter((b) => !b.read).length;
  }
  toggle(id: number) {
    const b = this.books.find((b) => b.id === id);
    if (b) b.read = !b.read;
  }
}
const store = new Store();

function Counter() {
  return <p>Unread: {store.unread}</p>;
}

const List = observer(function List() {
  return (
    <ul>
      {store.books.map((b) => (
        <li key={b.id}>
          <label>
            <input type="checkbox" checked={b.read} onChange={() => store.toggle(b.id)} /> {b.title}
          </label>
        </li>
      ))}
    </ul>
  );
});

export default function App() {
  return (
    <>
      <Counter />
      <List />
    </>
  );
}
Quick checkRead and write in Valtio

In a Valtio component, which line is correct?

Explain it out loudWhy not signals?

An interviewer asks: "Solid and Svelte use signals and skip the virtual DOM. Why doesn't React?"

Interview angle

Say it in 30 seconds

Reactive state tracks reads instead of asking you for selectors. While a component or effect runs, every observable value it reads records it as a dependency, and a write re-runs exactly those dependents. MobX does this with observable objects, cached computeds and observer components; Valtio lets you mutate a proxy and render from tracked immutable snapshots. Signals are the same idea as a primitive, used by Solid, Svelte, Preact and Angular, and the TC39 proposal is still at Stage 1. React chose re-render and diff instead: plain-value components, consistent snapshots for concurrent rendering, and the Compiler to cut the cost.

What is fine-grained reactivity, and how does dependency tracking work?

intermediate

Why doesn't React use signals?

senior

How does MobX's observer make a component re-render?

intermediate

MobX or Valtio: how do they differ?

intermediate

What's the status of signals in JavaScript itself?

basic

What happens when a MobX action updates state after an await?

senior

Recap#

  • Selectors are hand-written dependency lists. Reactive state discovers dependencies by tracking reads while code runs, and re-tracks on every run so branches are handled.
  • MobX wraps state in observables, derives with cached computeds, batches writes in actions, and re-renders observer components through a reaction connected with useSyncExternalStore.
  • Valtio lets you mutate a proxy and render from immutable snapshots; useSnapshot records the paths you read and skips re-renders when none changed.
  • Signals are the same idea as a primitive (Preact, Solid, Svelte runes, Angular, Vue). The TC39 Signals proposal is at Stage 1: an exploration, not a feature.
  • React keeps re-render and diff for plain-value components, consistent snapshots under concurrent rendering, and one model across server and client, and closes the performance gap with the Compiler.

Sources#