Org Skills

React performance fixes — working samples

Supporting material for react-performance. Agents load it on demand; it ships inside the skill folder.

RawSource

Copy-ready fixes for the findings in SKILL.md §3–§5. Every sample includes its imports. Apply one at a time and re-measure.

Sources: https://react.dev/reference/react · https://tanstack.com/virtual/latest · https://react.dev/learn/react-compiler/installation · https://developer.chrome.com/docs/web-platform/scheduler-yield

1. Virtualised list (@tanstack/react-virtual)

Use above roughly 100 rendered rows. Fixed row height (estimateSize returning a constant) is much cheaper than measured rows.

import { useRef } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

export function OrderRows({ orders }: { orders: Order[] }) {
  const parentRef = useRef<HTMLDivElement>(null);
  const virtualizer = useVirtualizer({
    count: orders.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 56,
    overscan: 8,
  });

  return (
    <div ref={parentRef} style={{ height: 600, overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
        {virtualizer.getVirtualItems().map((item) => (
          <div
            key={orders[item.index].id}
            style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: item.size, transform: `translateY(${item.start}px)` }}
          >
            <OrderRow order={orders[item.index]} />
          </div>
        ))}
      </div>
    </div>
  );
}

Variable heights: drop the height from the row style and pass ref={virtualizer.measureElement} plus data-index={item.index} on the row element.

react-window is an alternative, but only its v2 API (List with a rowComponent prop) exists today — FixedSizeList/VariableSizeList were removed, so any v1 snippet will not compile.

2. Typing lag: keep the input urgent, defer the view

import { useDeferredValue, useMemo, useState } from 'react';

export function OrderSearch({ orders }: { orders: Order[] }) {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);          // lags behind under load
  const results = useMemo(
    () => orders.filter((o) => o.customer.toLowerCase().includes(deferredQuery.toLowerCase())),
    [orders, deferredQuery],
  );
  const stale = query !== deferredQuery;

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search orders" />
      <div style={{ opacity: stale ? 0.6 : 1 }}>
        <OrderRows orders={results} />
      </div>
    </>
  );
}

Never debounce the input's own state — the echo must be instant. Debounce the request, defer the derived view.

For a navigation or tab switch that renders a lot, wrap the state update instead:

import { startTransition } from 'react';
startTransition(() => setTab('analytics'));

3. Keep expensive UI mounted without paying for it (<Activity>, React 19.2)

import { Activity } from 'react';

export function Workspace({ tab }: { tab: 'editor' | 'preview' }) {
  return (
    <>
      <Activity mode={tab === 'editor' ? 'visible' : 'hidden'}><Editor /></Activity>
      <Activity mode={tab === 'preview' ? 'visible' : 'hidden'}><Preview /></Activity>
    </>
  );
}

Hidden children keep their state and DOM, their effects are cleaned up, and React renders them at a lower priority. Use it when re-mounting is the expensive part (editors, maps, long scroll positions); plain unmounting is still the default.

4. Break up a long task

async function indexAll(records: Record[]) {
  for (const [i, record] of records.entries()) {
    index(record);
    if (i % 200 === 0) await yieldToMain();
  }
}

function yieldToMain(): Promise<void> {
  if ('scheduler' in globalThis && 'yield' in (globalThis as any).scheduler) {
    return (globalThis as any).scheduler.yield();
  }
  return new Promise((resolve) => setTimeout(resolve, 0));
}

scheduler.yield() returns to the browser but keeps the continuation at the front of the queue, so unlike setTimeout(…, 0) the work is not starved by unrelated tasks. Feature-detect it.

Work that never needs the DOM belongs in a worker instead:

// search.worker.ts
self.onmessage = (e: MessageEvent<{ q: string; rows: Row[] }>) => {
  self.postMessage(rank(e.data.q, e.data.rows));
};

// component
const worker = useMemo(() => new Worker(new URL('./search.worker.ts', import.meta.url), { type: 'module' }), []);
useEffect(() => () => worker.terminate(), [worker]);

5. Resource hints from React 19

import { preload, preinit, prefetchDNS } from 'react-dom';

preload('/fonts/inter-latin.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' });
preinit('https://cdn.example.com/widget.js', { as: 'script' });
prefetchDNS('https://images.example.com');

Call them during render of the component that will need the resource; React hoists the tags and de-duplicates them. Preload exactly one font file and the LCP image — a preload list is a priority list, and everything preloaded competes with everything else.

LCP image rules: real dimensions, sizes matching the layout, AVIF/WebP, fetchPriority="high", never loading="lazy". In next/image 16 the priority prop is deprecated in favour of preload.

6. Enable the React Compiler

Vite with @vitejs/plugin-react 6+:

// vite.config.js
import { defineConfig } from 'vite';
import react, { reactCompilerPreset } from '@vitejs/plugin-react';
import babel from '@rolldown/plugin-babel';

export default defineConfig({
  plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
});

Older plugin versions, or plain Babel:

// babel.config.js — the compiler plugin must run first
module.exports = { plugins: [['babel-plugin-react-compiler', { target: '19' }]] };

target: '17' or '18' compiles for older React, with react-compiler-runtime installed. Next.js: reactCompiler: true in next.config.ts.

Then make the bail-outs visible:

// eslint.config.js
import reactHooks from 'eslint-plugin-react-hooks';
export default [reactHooks.configs['recommended-latest']];

The lint output names the exact line that stopped a component from compiling (mutation during render, conditional hook, ref.current read in render). Fix those before adding a single useMemo — and delete manual memoisation from components the compiler now handles.