Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

render-counter.ts

177 lines5.9 KB

1// Dev-only render counter driven by `scripts/measure-renders.mts` through the
2// Hermes inspector. It wraps the DevTools hook's commit callback, so it must load
3// before React renders anything; see `render-counter-entry.ts`.
4//
5// The fiber walk matches the web counter used for React Compiler work: a
6// bailed-out subtree keeps `child === alternate.child`, so it is not descended,
7// because fibers there keep stale flags and alternates from older commits.
8// PerformedWork (1) is cleared whenever React clones a fiber, so a reached fiber
9// with it set rendered in this commit.
10​
11interface Fiber {
12 readonly tag: number;
13 readonly type: unknown;
14 readonly flags: number;
15 readonly alternate: Fiber | null;
16 readonly child: Fiber | null;
17 readonly sibling: Fiber | null;
18 readonly memoizedProps: Record<string, unknown> | null;
19 readonly memoizedState: HookSlot | null;
21interface HookSlot {
22 readonly memoizedState: unknown;
23 /** Non-null only for useState and useReducer, the hooks that can schedule a render. */
24 readonly queue: unknown;
25 readonly next: HookSlot | null;
27interface DevToolsHook {
28 onCommitFiberRoot?: (id: unknown, root: { current: Fiber }, ...rest: unknown[]) => unknown;
29 __t3RenderCounter?: true;
31interface RenderCounterState {
32 on: boolean;
33 commits: number;
34 counts: Map<string, number>;
35 causes: Map<string, number>;
37export interface RenderCounterReport {
38 readonly commits: number;
39 readonly totalRenders: number;
40 readonly components: ReadonlyArray<{ key: string; count: number }>;
41 readonly causes: ReadonlyArray<{ key: string; count: number }>;
43​
44const COMPONENT_TAGS = new Set([0, 1, 11, 14, 15]);
45const PERFORMED_WORK = 1;
46​
47function nameOf(fiber: Fiber): string | null {
48 const type = fiber.type as {
49 displayName?: string;
50 name?: string;
51 type?: { displayName?: string; name?: string };
52 render?: { displayName?: string; name?: string };
53 } | null;
54 if (!type || typeof type === "string") return null;
55 const inner = type.type ?? type.render ?? type;
56 const raw = type.displayName || inner.displayName || inner.name || "";
57 return raw.replace(/^(Forget\(|Memo\()+|\)+$/g, "") || null;
59​
60function isEffect(value: unknown): boolean {
61 return (
62 typeof value === "object" &&
63 value !== null &&
64 "create" in value &&
65 "deps" in value &&
66 "tag" in value
67 );
69​
70function changedStateSlot(alternate: Fiber, node: Fiber): number {
71 let a = alternate.memoizedState;
72 let b = node.memoizedState;
73 for (let index = 0; a && b && index < 800; index++) {
74 const before = a.memoizedState;
75 const after = b.memoizedState;
76 // Memo, callback and ref slots change because something upstream did; only a
77 // state update is a cause of its own.
78 if (b.queue !== null && !isEffect(after) && !Object.is(before, after)) return index;
79 a = a.next;
80 b = b.next;
81 }
82 return -1;
84​
85function causeOf(node: Fiber, parentName: string): string {
86 const alternate = node.alternate;
87 if (!alternate) return "mount";
88 const slot = changedStateSlot(alternate, node);
89 if (slot >= 0) return `state#${slot}`;
90 if (alternate.memoizedProps !== node.memoizedProps) {
91 const props = node.memoizedProps ?? {};
92 const keys = Object.keys(props).filter(
93 (key) => !Object.is(alternate.memoizedProps?.[key], props[key]),
94 );
95 return keys.length ? `props:${keys.slice(0, 4).join(",")}` : `parent-same-props<-${parentName}`;
96 }
97 return "context";
99​
100function increment(map: Map<string, number>, key: string) {
101 map.set(key, (map.get(key) ?? 0) + 1);
103​
104function install(state: RenderCounterState) {
105 const hook = (globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })
106 .__REACT_DEVTOOLS_GLOBAL_HOOK__;
107 if (!hook || typeof hook.onCommitFiberRoot !== "function") {
108 setTimeout(() => install(state), 50);
109 return;
110 }
111 if (hook.__t3RenderCounter) return;
112 hook.__t3RenderCounter = true;
113 const original = hook.onCommitFiberRoot.bind(hook);
114​
115 const visit = (fiber: Fiber | null, parentName: string) => {
116 let node = fiber;
117 while (node) {
118 const alternate = node.alternate;
119 const name = COMPONENT_TAGS.has(node.tag) ? nameOf(node) : null;
120 const rendered = name !== null && (node.flags & PERFORMED_WORK) === PERFORMED_WORK;
121 if (rendered) {
122 increment(state.counts, name);
123 increment(state.causes, `${name} ${causeOf(node, parentName)}`);
124 }
125 const skipped = alternate !== null && node.child === alternate.child && !rendered;
126 if (node.child && !skipped) visit(node.child, rendered ? name : parentName);
127 node = node.sibling;
128 }
129 };
130​
131 hook.onCommitFiberRoot = (id, root, ...rest) => {
132 if (state.on) {
133 state.commits += 1;
134 visit(root.current.child, "root");
135 }
136 return original(id, root, ...rest);
137 };
139​
140const state: RenderCounterState = { on: false, commits: 0, counts: new Map(), causes: new Map() };
141​
142const sorted = (map: Map<string, number>) =>
143 [...map].map(([key, count]) => ({ key, count })).sort((a, b) => b.count - a.count);
144​
145install(state);
146​
147Object.assign(globalThis, {
148 /** Routes an app link in-process, so drivers need no simctl or adb access. */
149 __t3RenderCounterOpen(url: string) {
150 const { Linking } = require("react-native") as typeof import("react-native");
151 void Linking.openURL(url);
152 return true;
153 },
154 /** Restarts the JS app on Home; deferred so the inspector call can reply first. */
155 __t3RenderCounterReload() {
156 const { DevSettings } = require("react-native") as typeof import("react-native");
157 setTimeout(() => DevSettings.reload(), 100);
158 return true;
159 },
160 __t3RenderCounterStart() {
161 state.commits = 0;
162 state.counts = new Map();
163 state.causes = new Map();
164 state.on = true;
165 return true;
166 },
167 __t3RenderCounterStop(): RenderCounterReport {
168 state.on = false;
169 const components = sorted(state.counts);
170 return {
171 commits: state.commits,
172 totalRenders: components.reduce((total, entry) => total + entry.count, 0),
173 components,
174 causes: sorted(state.causes),
175 };
176 },
177});