Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 56 additions & 5 deletions packages/scan/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ Airbnb&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://polaris.shopify.com/"

![React Scan in action](https://raw.githubusercontent.com/aidenybai/react-scan/refs/heads/main/.github/assets/demo.gif)

> [!IMPORTANT]
> Want to monitor issues in production? Check out [React Scan Monitoring](https://react-scan.com/monitoring)!

## Install

### Package managers
Expand Down Expand Up @@ -89,6 +86,62 @@ If you want to install the extension, follow the guide [here](https://github.com

See [discussion](https://github.com/aidenybai/react-scan/pull/23)

## `react-scan/lite`: headless instrumentation

A tiny, UI-less entry point that taps into the same React DevTools profiling channel the Timeline Profiler uses. No toolbar, no canvas, no styles. Just a stream of commit / render / state-update events you can pipe to a callback or POST to an endpoint. Pairs naturally with a `long-animation-frame` `PerformanceObserver` so you can attribute a slow LoAF to a specific component subtree.

```ts
import { instrument } from "react-scan/lite";

const handle = instrument({
onEvent: (event) => console.log(event),

// optional: POST every event to an ingest endpoint
endpoint: "http://127.0.0.1:54321/ingest/abc123",
sessionId: "abc123",

// optional: enrich each fiber summary
recordChangeDescriptions: true, // why did this re-render? (props/state/context/hooks/parent)
includeFiberSource: true, // file:line of each fiber's JSX call site
includeFiberIdentity: true, // stable id across commits, for cascade histograms
});

handle.subscribe((event) => {
if (event.kind === "commit") {
// event.tree[] = per-fiber { name, fiberId, depth, actualDuration,
// source, ownerName, changeDescription }
// event.priorityName = "UserBlocking" | "Normal" | ...
}
if (event.kind === "profiling-hooks-status" && !event.available) {
// React 19.2+ prod or non-__PROFILE__ build: mark* hooks won't fire.
// Fall back to LoAF-only attribution.
}
});

handle.stop(); // idempotent
```

`instrument` must run before `react-dom` mounts (top of your entry, or as the first script in `<head>`). It's SSR-safe: calling `instrument()` in Node returns a noop handle whose `isActive()` is `false`.

### Per-fiber enrichment

| Option | Default | What you get |
| ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- |
| `recordChangeDescriptions` | `false` | `changeDescription: { isFirstMount, props[], state, context, hooks[], parent }` per fiber. Answers "why this re-rendered" in a single event. |
| `includeFiberSource` | `false` | `source: { fileName, lineNumber, columnNumber }` + `ownerName`, read from `_debugSource` (R16/17/18) or `_debugStack` (R19+). Sync, no symbolication. |
| `includeFiberIdentity` | `false` | `fiberId: number`, stable monotonic id per logical fiber (alternate-aware), so the agent can build cross-commit histograms. |
| `includeLaneLabels` | `true` | `laneLabels: string[]` (translated via `renderer.getLaneLabelMap()`) and `priorityName` (e.g. `"UserBlocking"`) |
| `maxFibersPerCommit` | `5000` | Cap on tree size per commit to bound payload size |
| `minFiberActualDurationMs` | `0` | Skip fibers below this threshold |

### Build profile

`actualDuration` and the `mark*` profiling hooks only populate in `__PROFILE__` builds. In development that's the default; in production you can opt in by aliasing `react-dom` to `react-dom/profiling` in your bundler (`resolve.alias` in webpack/vite). Otherwise `onCommitFiberRoot` still fires but every fiber's `actualDuration` is `0`. The `profiling-hooks-status` event makes this explicit: `available: false` with `reason: "no-inject-method"` means React 19.2+ in prod or a non-`__PROFILE__` build, so the agent should fall back to LoAF-only attribution rather than concluding "idle".

### Coexistence with React DevTools

If React DevTools is also attached, `instrument()` logs a one-time warning: the `injectProfilingHooks` channel is a hard replace, so DevTools' Timeline Profiler stops receiving events while this instrumentation is active. Call `handle.stop()` to restore.

## API Reference

<details>
Expand Down Expand Up @@ -183,8 +236,6 @@ This often comes down to props that update in reference, like callbacks or objec

React Scan helps you identify these issues by automatically detecting and highlighting renders that cause performance issues. Now, instead of guessing, you can see exactly which components you need to fix.

> Want monitor issues in production? Check out [React Scan Monitoring](https://react-scan.com/monitoring)!

### FAQ

**Q: Why this instead of React Devtools?**
Expand Down
7 changes: 6 additions & 1 deletion packages/scan/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@
"import": "./dist/install-hook.mjs",
"require": "./dist/install-hook.js"
},
"./lite": {
"types": "./dist/lite/index.d.ts",
"import": "./dist/lite/index.mjs",
"require": "./dist/lite/index.js"
},
"./auto": {
"production": {
"import": {
Expand Down Expand Up @@ -206,7 +211,7 @@
"@preact/signals": "^1.3.1",
"@rollup/pluginutils": "^5.1.3",
"@types/node": "^20.17.9",
"bippy": "^0.5.30",
"bippy": "^0.5.39",
"commander": "^14.0.0",
"estree-walker": "^3.0.3",
"picocolors": "^1.1.1",
Expand Down
155 changes: 155 additions & 0 deletions packages/scan/src/lite/change-description.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import {
ClassComponentTag,
type Fiber,
ForwardRefTag,
FunctionComponentTag,
MemoComponentTag,
SimpleMemoComponentTag,
traverseContexts,
traverseProps,
traverseState,
} from 'bippy';
import type { ChangeDescription } from './types';

const objectIs = Object.is;

export const isCompositeTag = (tag: number): boolean =>
tag === FunctionComponentTag ||
tag === ClassComponentTag ||
tag === ForwardRefTag ||
tag === MemoComponentTag ||
tag === SimpleMemoComponentTag;

const collectChangedProps = (fiber: Fiber): Array<string> => {
// Precondition: caller must have already handled the mount path. Bippy's
// `traverseProps` falls back to `prev = {}` when `fiber.alternate` is null,
// which would mark every prop as "changed". `getChangeDescription` short-
// circuits to `isFirstMount: true` before calling us; we mirror the guard
// defensively in case anyone reuses this helper standalone.
if (fiber.alternate === null) return [];
const changed: Array<string> = [];
traverseProps(fiber, (propName, nextValue, prevValue) => {
if (!objectIs(prevValue, nextValue)) changed.push(propName);
});
return changed;
};

const didAnyContextChange = (fiber: Fiber): boolean => {
let changed = false;
traverseContexts(fiber, (nextContext, prevContext) => {
if (!nextContext || !prevContext) return;
// Order swap means a non-context change caused the rerender; bail.
if (nextContext.context !== prevContext.context) {
changed = false;
return true;
}
if (!objectIs(prevContext.memoizedValue, nextContext.memoizedValue)) {
changed = true;
return true;
}
});
return changed;
};

const didAnyClassStateChange = (fiber: Fiber): boolean => {
// For class components, memoizedState is a single state object (not a Hook
// chain), so traverseState only yields one node. Compare keys shallowly.
const previousState = fiber.alternate?.memoizedState;
const nextState = fiber.memoizedState;
if (
!previousState ||
!nextState ||
typeof previousState !== 'object' ||
typeof nextState !== 'object'
) {
return previousState !== nextState;
}
const previousObject = previousState as Record<string, unknown>;
const nextObject = nextState as Record<string, unknown>;
const allKeys = new Set<string>([
...Object.keys(previousObject),
...Object.keys(nextObject),
]);
for (const key of allKeys) {
if (!objectIs(previousObject[key], nextObject[key])) return true;
}
return false;
};

/**
* Walks the Hook linked list on `fiber.memoizedState` and returns the indices
* of hooks whose `memoizedState` changed by reference. Bippy's `traverseState`
* iterates both fibers' Hook chains in parallel.
*
* APPROXIMATE: this conflates `useState` value changes with `useMemo` /
* `useCallback` / `useEffect` deps changes (they share the same slot).
* DevTools uses `react-debug-tools.inspectHooks` for precise attribution; we
* deliberately skip that; bippy ships it as `inspectHooks` from `bippy/source`
* if a caller wants the exact answer.
*/
const collectChangedHookIndices = (fiber: Fiber): Array<number> => {
const indices: Array<number> = [];
let index = 0;
traverseState(fiber, (nextState, prevState) => {
if (
nextState &&
prevState &&
!objectIs(prevState.memoizedState, nextState.memoizedState)
) {
indices.push(index);
}
index++;
});
return indices;
};

/**
* Returns a change description for fibers whose tag we can attribute, or
* `null` for everything else (host nodes, suspense, fragments, etc.).
*
* Ported from react-devtools-shared/src/backend/fiber/renderer.js
* `getChangeDescription`, with bippy's `traverseProps`/`traverseState`/
* `traverseContexts` doing the heavy lifting.
*
* The `parentRendered` flag is computed by the caller (the fiber walker)
* which already traverses the tree top-down; re-walking `fiber.return`
* here would be O(depth) per fiber and pointless.
*/
export const getChangeDescription = (
fiber: Fiber,
parentRendered: boolean,
): ChangeDescription | null => {
const tag = fiber.tag;
if (!isCompositeTag(tag)) return null;

if (fiber.alternate === null) {
return {
isFirstMount: true,
props: null,
state: false,
context: false,
hooks: [],
parent: false,
};
}

if (tag === ClassComponentTag) {
return {
isFirstMount: false,
props: collectChangedProps(fiber),
state: didAnyClassStateChange(fiber),
context: didAnyContextChange(fiber),
hooks: [],
parent: parentRendered,
};
}

return {
isFirstMount: false,
props: collectChangedProps(fiber),
state: false,
context: didAnyContextChange(fiber),
hooks: collectChangedHookIndices(fiber),
parent: parentRendered,
};
};
18 changes: 18 additions & 0 deletions packages/scan/src/lite/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export const DEFAULT_LOCATION = 'ReactScanLite';
export const DEFAULT_MAX_FIBERS_PER_COMMIT = 5000;
export const DEFAULT_MIN_FIBER_ACTUAL_DURATION_MS = 0;

// Total number of React fiber lanes. Lanes are encoded as a 31-bit bitmask;
// each bit represents one scheduling lane. Bumped in 18.x but stable since.
export const REACT_TOTAL_NUM_LANES = 31;

// Scheduler priority levels. Source:
// https://github.com/facebook/react/blob/main/packages/scheduler/src/SchedulerPriorities.js
export const SCHEDULER_PRIORITY_NAMES: Record<number, string> = {
0: 'NoPriority',
1: 'Immediate',
2: 'UserBlocking',
3: 'Normal',
4: 'Low',
5: 'Idle',
};
106 changes: 106 additions & 0 deletions packages/scan/src/lite/create-emitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { DEFAULT_LOCATION } from './constants';
import type { LaneLabelTranslator } from './lane-labels';
import type { LiteEvent, LiteEventKind, LiteOptions } from './types';

/**
* Surface used inside the lite module's hot path (event emission, listener
* management). Does NOT include lifecycle controls like
* `setLaneLabelTranslator` / `dispose` — those are returned separately so
* downstream callers (e.g. profiling-hook closures) can't accidentally
* tear down the emitter from inside an event handler.
*/
export interface Emitter {
emit: (kind: LiteEventKind, partial?: Partial<LiteEvent>) => void;
subscribe: (listener: (event: LiteEvent) => void) => () => void;
}

/**
* Returned alongside the `emitter` to its sole owner (`instrument()`).
* Holds the controls that must NOT leak into the per-event hot path.
*/
export interface EmitterControl {
setLaneLabelTranslator: (translator: LaneLabelTranslator | null) => void;
dispose: () => void;
}

export const createEmitter = (
options: LiteOptions,
): { emitter: Emitter; control: EmitterControl } => {
const listeners = new Set<(event: LiteEvent) => void>();
if (options.onEvent) listeners.add(options.onEvent);

const endpoint = options.endpoint;
const sessionId = options.sessionId;
const locationPrefix = options.location ?? DEFAULT_LOCATION;
const canPostToEndpoint = Boolean(endpoint && sessionId);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
let isActive = true;
let translator: LaneLabelTranslator | null = null;

const emit = (kind: LiteEventKind, partial?: Partial<LiteEvent>): void => {
if (!isActive) return;
// Cheap fast-path: if nobody is listening AND we have no endpoint to
// POST to, skip the timestamp call, the event allocation, and the
// translator work entirely. Common when a consumer creates a handle
// but never calls `subscribe()` / passes `onEvent` / sets `endpoint`.
if (listeners.size === 0 && !canPostToEndpoint) return;
const timestamp = performance.now();
const event: LiteEvent = {
kind,
timestamp,
...partial,
};
if (translator) {
if (event.lanes != null && event.laneLabels === undefined) {
const labels = translator.laneLabels(event.lanes);
if (labels) event.laneLabels = labels;
}
if (event.priorityLevel != null && event.priorityName === undefined) {
const name = translator.priorityName(event.priorityLevel);
if (name) event.priorityName = name;
}
}
for (const listener of listeners) {
try {
listener(event);
} catch {}
}
if (canPostToEndpoint) {
try {
fetch(endpoint as string, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId,
location: `${locationPrefix}:${kind}`,
message: kind,
data: event,
timestamp,
}),
keepalive: true,
}).catch(() => {});
} catch {}
}
};

const subscribe = (listener: (event: LiteEvent) => void): (() => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
};

const setLaneLabelTranslator = (next: LaneLabelTranslator | null): void => {
translator = next;
};

const dispose = (): void => {
isActive = false;
listeners.clear();
translator = null;
};

return {
emitter: { emit, subscribe },
control: { setLaneLabelTranslator, dispose },
};
};
Loading
Loading