devtools/docs/bidirectional-communication.md
Alem Tuzlak 9bf08e270f
docs: comprehensive documentation overhaul (#363)
* docs: add documentation redesign design document

Comprehensive plan for restructuring TanStack Devtools documentation
with layered architecture approach: Getting Started, Concepts, Guides,
API Reference, and Examples sections. Adds 11 new pages including
architecture overview, event system deep-dive, Vue framework support,
and plugin building guides.

* docs: add documentation implementation plan

18-task plan covering: navigation restructure, 4 new Concepts pages
(architecture, event system, plugin lifecycle, source inspector),
3 new Guides (custom plugins, devtools-utils, bidirectional comms),
Vue framework support, Solid custom plugins, and updates to existing
pages including overview, quick-start, installation, and React adapter.

* docs: restructure navigation with Concepts and Guides sections, add Vue

* docs: expand overview with package map and architecture diagram

* docs: add all framework examples to quick start

* docs: add Vue and Preact installation instructions

* docs: add architecture overview page

* docs: add event system concepts page

* docs: add plugin lifecycle concepts page

* docs: add source inspector concepts page

* docs: add framework-agnostic custom plugin building guide

* docs: add devtools-utils guide for plugin factory helpers

* docs: add bidirectional communication guide

* docs: add Vue basic setup and adapter pages

* docs: add Vue and Solid custom plugins guides

* docs: replace TODO in React adapter with actual content

* docs: expand Vite plugin features documentation

* docs: fix event map key convention, typos, and internal link extensions

- Event map keys should be suffix-only (e.g., 'state-update'), not
  prefixed with pluginId. EventClient prepends pluginId automatically.
  Fixed across all custom plugin guides and concept pages.
- Fix enabled:false docs in event-system.md (emit is a no-op, not
  internal dispatch)
- Fix double "the the" typo in installation.md
- Remove .md extensions from internal doc links for consistency
- Fix event map key in configuration.md example

* docs: remove internal plan files

* docs: replace ASCII diagrams with mermaid in architecture overview

* docs: add mermaid diagrams across all documentation pages

- overview.md: architecture layer diagram
- event-system.md: connection lifecycle state diagram
- plugin-lifecycle.md: mount sequence flowchart + portal pattern diagram
- source-inspector.md: inspection flow diagram
- building-custom-plugins.md: plugin architecture overview
- bidirectional-communication.md: two-way flow + time travel sequence diagram
- vite-plugin.md: sub-plugin overview diagram
2026-03-04 13:52:26 +01:00

3.9 KiB

title id
Bidirectional Communication bidirectional-communication

Most devtools plugins observe state in one direction: app to devtools. But EventClient supports two-way communication. Your devtools panel can also send commands back to the app. This enables features like state editing, action replay, and time-travel debugging.

graph LR
    subgraph app["Application"]
        state["State / Library"]
    end
    subgraph ec["EventClient"]
        direction TB
        bus["Event Bus"]
    end
    subgraph dt["Devtools Panel"]
        ui["Panel UI"]
    end

    state -- "emit('state-update')" --> bus
    bus -- "on('state-update')" --> ui
    ui -- "emit('reset')" --> bus
    bus -- "on('reset')" --> state

Pattern: App to Devtools (Observation)

The standard one-way pattern. Your app emits events, the devtools panel listens.

// In your app/library
eventClient.emit('state-update', { count: 42 })

// In your devtools panel
eventClient.on('state-update', (e) => {
  setState(e.payload)
})

Pattern: Devtools to App (Commands)

The panel emits command events, the app listens and reacts.

// In your devtools panel (e.g., a "Reset" button click handler)
eventClient.emit('reset', undefined)

// In your app/library
eventClient.on('reset', () => {
  store.reset()
})

You need to define both directions in your event map:

type MyEvents = {
  // App → Devtools
  'state-update': { count: number }
  // Devtools → App
  'reset': void
  'set-state': { count: number }
}

Pattern: Time Travel

The most powerful bidirectional pattern. Combine observation with command-based state restoration.

sequenceDiagram
    participant App as Application
    participant EC as EventClient
    participant Panel as Time Travel Panel

    App->>EC: emit('snapshot', { state, timestamp })
    EC->>Panel: on('snapshot') → collect snapshots
    Note over Panel: User drags slider to past state
    Panel->>EC: emit('revert', { state })
    EC->>App: on('revert') → restore state
    App->>EC: emit('snapshot', { state, timestamp })
    EC->>Panel: on('snapshot') → update timeline

Event Map

type TimeTravelEvents = {
  'snapshot': { state: unknown; timestamp: number; label: string }
  'revert': { state: unknown }
}

App Side

Emit snapshots on every state change:

function applyAction(action) {
  state = reducer(state, action)

  timeTravelClient.emit('snapshot', {
    state: structuredClone(state),
    timestamp: Date.now(),
    label: action.type,
  })
}

// Listen for revert commands from devtools
timeTravelClient.on('revert', (e) => {
  state = e.payload.state
  rerender()
})

Panel Side

Collect snapshots and provide a slider:

function TimeTravelPanel() {
  const [snapshots, setSnapshots] = useState([])
  const [index, setIndex] = useState(0)

  useEffect(() => {
    return timeTravelClient.on('snapshot', (e) => {
      setSnapshots((prev) => [...prev, e.payload])
      setIndex((prev) => prev + 1)
    })
  }, [])

  const handleSliderChange = (newIndex) => {
    setIndex(newIndex)
    timeTravelClient.emit('revert', { state: snapshots[newIndex].state })
  }

  return (
    <div>
      <input
        type="range"
        min={0}
        max={snapshots.length - 1}
        value={index}
        onChange={(e) => handleSliderChange(Number(e.target.value))}
      />
      <p>
        State at: {snapshots[index]?.label} (
        {new Date(snapshots[index]?.timestamp).toLocaleTimeString()})
      </p>
      <pre>{JSON.stringify(snapshots[index]?.state, null, 2)}</pre>
    </div>
  )
}

Best Practices

  • Keep payloads serializable. No functions, DOM nodes, or circular references.
  • Use structuredClone() for snapshots to avoid reference mutations.
  • Debounce frequent emissions if needed (e.g., rapid state changes).
  • Use distinct event suffixes for observation vs commands (e.g., state-update for observation, set-state for commands).