Mastering Fine-Grained Reactivity in SolidJS: High-Performance Web Apps Without Virtual DOM

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

Context & Why

Six months ago, our analytics dashboard hit a wall. We were streaming roughly 400 WebSocket ticks per second from factory IoT sensors, and the browser could not keep up. Frame rates plummeted from 60 FPS down to 14 FPS. Inputs lagged by over 300ms, frustrating operators on the plant floor.

Our React-based Virtual DOM (VDOM) setup was the bottleneck. With every incoming payload, the app re-executed entire component functions, walked massive component trees, and computed complex object diffs before touching a single real element. The browser spent most of its time calculating what not to change.

To solve this, we moved the telemetry stream to SolidJS. Most frontend frameworks bind reactivity directly to component boundaries: change one value, and the whole component re-evaluates. SolidJS flips this model completely. Its compiler transforms JSX into targeted, low-level DOM operations at build time.

Here is the critical mental shift: SolidJS components run exactly once during setup. They are initialization functions, not render loops. When a reactive Signal updates, only the precise DOM text node or attribute bound to that signal changes. No tree diffing. No virtual nodes. No component lifecycle churn.

Installation

Setting up a benchmark workspace takes less than two minutes with Vite. Open your terminal and run:

# Scaffold a new SolidJS project with TypeScript
pnpm create vite solid-reactivity-demo --template solid-ts

# Navigate to the project root
cd solid-reactivity-demo

# Install project dependencies
pnpm install

# Start the local development server
pnpm dev

Prefer standard npm or yarn? The equivalent commands run cleanly:

npm create vite@latest solid-reactivity-demo -- --template solid-ts
cd solid-reactivity-demo
npm install
npm run dev

Vite will spin up a local server at http://localhost:5173 with hot module replacement that updates in under 20ms.

Configuration

Under the hood, Solid relies on a custom JSX transform to generate raw DOM creation calls rather than React.createElement or h() helpers. Check your vite.config.ts to ensure vite-plugin-solid is registered:

import { defineConfig } from 'vite';
import solidPlugin from 'vite-plugin-solid';

export default defineConfig({
  plugins: [solidPlugin()],
  server: {
    port: 3000,
    open: true,
  },
  build: {
    target: 'esnext',
    minify: 'esbuild',
  },
});

Next, open tsconfig.json. You must configure the JSX factory to match Solid’s runtime types:

{
  "compilerOptions": {
    "strict": true,
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "jsx": "preserve",
    "jsxImportSource": "solid-js",
    "types": ["vite/client"]
  },
  "include": ["src"]
}

Now let’s build a telemetry stream widget that simulates 100ms updates, computes derived averages, and manages timer cleanup:

// src/components/TelemetryStream.tsx
import { createSignal, createMemo, createEffect, onCleanup, For, batch } from 'solid-js';

interface MetricTick {
  id: number;
  label: string;
  value: number;
  timestamp: number;
}

export function TelemetryStream() {
  const [metrics, setMetrics] = createSignal<MetricTick[]>([]);
  const [rateLimit, setRateLimit] = createSignal(100); // ms interval
  const [isRunning, setIsRunning] = createSignal(true);
  const [lastSync, setLastSync] = createSignal<number>(Date.now());

  // Derived state: recalculates only when metrics() updates
  const averageValue = createMemo(() => {
    const current = metrics();
    if (current.length === 0) return 0;
    const sum = current.reduce((acc, tick) => acc + tick.value, 0);
    return Math.round((sum / current.length) * 100) / 100;
  });

  // Background streaming simulation
  createEffect(() => {
    if (!isRunning()) return;

    const intervalId = setInterval(() => {
      const now = Date.now();
      const tick: MetricTick = {
        id: now,
        label: `Sensor-0${Math.floor(Math.random() * 8) + 1}`,
        value: Math.floor(Math.random() * 450) + 50,
        timestamp: now,
      };

      // Batching multiple updates prevents intermediate observer runs
      batch(() => {
        setMetrics((prev) => [...prev.slice(-49), tick]);
        setLastSync(now);
      });
    }, rateLimit());

    // Clean up timers on disposal to avoid orphaned workers
    onCleanup(() => clearInterval(intervalId));
  });

  console.log('TelemetryStream mounted (runs only once!)');

  return (
    <div class="p-6 max-w-2xl mx-auto bg-slate-900 text-white rounded-xl shadow-lg">
      <h3 class="text-xl font-bold mb-4">Real-Time Telemetry Monitor</h3>
      
      <div class="flex gap-4 items-center mb-6">
        <button
          onClick={() => setIsRunning((v) => !v)}
          class="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded font-semibold transition-colors"
        >
          {isRunning() ? 'Pause Stream' : 'Resume Stream'}
        </button>
        <span class="text-sm text-gray-400">
          Interval: {rateLimit()}ms | Last sync: {new Date(lastSync()).toLocaleTimeString()}
        </span>
      </div>

      <div class="grid grid-cols-2 gap-4 mb-6">
        <div class="bg-slate-800 p-4 rounded-lg">
          <span class="text-xs text-slate-400 uppercase tracking-wide">Rolling Average</span>
          <p class="text-2xl font-mono text-emerald-400">{averageValue()}</p>
        </div>
        <div class="bg-slate-800 p-4 rounded-lg">
          <span class="text-xs text-slate-400 uppercase tracking-wide">Retained Buffer</span>
          <p class="text-2xl font-mono text-cyan-400">{metrics().length} items</p>
        </div>
      </div>

      <div class="max-h-60 overflow-y-auto divide-y divide-slate-800">
        <For each={metrics()}>
          {(item) => (
            <div class="py-2 flex justify-between text-sm font-mono">
              <span class="text-slate-400">{item.label}</span>
              <span class="text-amber-400">{item.value} ms</span>
            </div>
          )}
        </For>
      </div>
    </div>
  );
}

Open your developer console. In React, that console.log would fire ten times every second as metrics stream in. In SolidJS, it prints exactly once on mount. Updating metrics() only mutates the text node inside averageValue(), the length display, and the list diff inside <For>. The surrounding markup remains untouched.

Verification & Monitoring

Measuring reactive isolation requires examining where the browser main thread spends its time. Over six months in production, we validated performance using three checks:

1. Profiling Scripting Overhead with Chrome DevTools

Record a 10-second trace in the Performance tab while pumping 100 events per second through the feed. In our head-to-head audits:

  • Virtual DOM: Spent 46.2% of total CPU time on JavaScript execution. Most of that went to recursive tree walks and discarding ephemeral objects.
  • SolidJS: Scripting overhead dropped to 6.8%. The CPU spent almost its entire cycle waiting on GPU compositing, holding a stable 60 FPS with zero dropped frames.

2. Guarding Against Reactive Graph Leaks

Solid uses synchronous observer closures. If you instantiate signals inside untracked helper functions or forget to clean up event listeners, those closures will linger. We inspect this using Chrome’s Memory panel by recording an Allocation Timeline. On a healthy dashboard, closure allocations level off after initial warmup rather than climbing like a staircase.

3. Long-Running Heap Stability

Memory stability matters for monitoring tools left open all day. In our tests, memory usage stayed flat at roughly 38 MB over 72 hours of continuous streaming. Eliminating ephemeral VDOM tree allocations cut minor garbage collection pauses from 22ms down to under 1.5ms. If your UI handles high-frequency events, adopting fine-grained reactivity removes the render tax entirely.

Share: