Skip to content

Commit 3a24977

Browse files
chore(lint): React effects can't grow past each file's budget
We are removing useEffect and its siblings from web and mobile, but nothing stopped new code from adding them back as fast as they come out. The t3code/react-effect-budget oxlint rule counts useEffect, useLayoutEffect, and useInsertionEffect calls, including member calls like React.useEffect, in every non-test file under apps/web/src, apps/mobile/src, and packages/*/src. scripts/effect-budget.json holds each file's budget by repo-relative path; a missing entry is 0. Past the budget, the rule reports each extra call with the alternatives to try, and says to raise the entry in the same PR when an effect is genuinely right. Since it is a lint rule, CI, check:changed, and editors enforce it with no separate step. `vp run effect-budget:update` lowers entries to the current counts with the rule's own matcher and drops ones that reach 0. It never adds or raises one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7bafc40 commit 3a24977

13 files changed

Lines changed: 738 additions & 7 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/
194194
options, and pass combinators as additional function-builder arguments.
195195
- Inferred types over annotations. `any` is the enemy.
196196
- Default to no comment. Write one only for a constraint, an external quirk, or an invariant the code can't show, in one line where you can and four at most. Don't restate names or signatures, narrate steps, record history, or explain the fix you just made; the PR carries that. `t3code/no-low-value-comments` enforces the length cap and the mechanical cases.
197+
- React effects are a last resort: derive in render, act in handlers, reset with `key`, or use a ref callback or store. The `t3code/react-effect-budget` lint rule holds each file to its entry in `scripts/effect-budget.json`; raise an entry only in the PR that needs the effect, and run `vp run effect-budget:update` to lock in removals.
197198
- Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays.
198199
- If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it.
199200

‎oxlint-plugin-t3code/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-e
1515
import noAmbiguousDetailNavigation from "./rules/no-ambiguous-detail-navigation.ts";
1616
import noMobilePullRequestGlyphLiterals from "./rules/no-mobile-pull-request-glyph-literals.ts";
1717
import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";
18+
import reactEffectBudget from "./rules/react-effect-budget.ts";
1819
import requireRegisteredListScroll from "./rules/require-registered-list-scroll.ts";
1920
import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts";
2021
import noPollingLoopInTests from "./rules/no-polling-loop-in-tests.ts";
@@ -52,6 +53,7 @@ export default definePlugin({
5253
"no-ambiguous-detail-navigation": noAmbiguousDetailNavigation,
5354
"no-mobile-pull-request-glyph-literals": noMobilePullRequestGlyphLiterals,
5455
"no-native-title-tooltip": noNativeTitleTooltip,
56+
"react-effect-budget": reactEffectBudget,
5557
"require-registered-list-scroll": requireRegisteredListScroll,
5658
"no-outset-state-indicators": noOutsetStateIndicators,
5759
"no-polling-loop-in-tests": noPollingLoopInTests,

‎oxlint-plugin-t3code/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
"name": "@t3tools/oxlint-plugin-t3code",
33
"private": true,
44
"type": "module",
5+
"exports": {
6+
"./react-effect-budget": "./rules/react-effect-budget.ts"
7+
},
58
"scripts": {
69
"typecheck": "tsc --noEmit",
710
"test": "vp test run --config ../vite.config.ts --dir ."
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { assert, describe } from "@effect/vitest";
2+
3+
import { createOxlintRuleHarness } from "../test/utils.ts";
4+
5+
const twoEffects = `import React, { useEffect } from "react";
6+
export function Panel() {
7+
useEffect(() => {}, []);
8+
React.useLayoutEffect(() => {});
9+
return null;
10+
}
11+
`;
12+
13+
const threeEffects = `import React, { useEffect, useInsertionEffect } from "react";
14+
export function Panel() {
15+
useEffect(() => {}, []);
16+
React.useLayoutEffect(() => {});
17+
useInsertionEffect(() => {});
18+
React.useEffect(() => {});
19+
return null;
20+
}
21+
`;
22+
23+
const reports = (output: string) => output.match(/t3code\(react-effect-budget\)/g)?.length ?? 0;
24+
25+
const budgeted = (filename: string) =>
26+
createOxlintRuleHarness("t3code/react-effect-budget", {
27+
filename,
28+
ruleOptions: (fixtureDir) => [{ root: fixtureDir }],
29+
files: { "scripts/effect-budget.json": JSON.stringify({ "src/Panel.tsx": 2 }) },
30+
});
31+
32+
const rule = budgeted("src/Panel.tsx");
33+
34+
describe("t3code/react-effect-budget", () => {
35+
rule.valid("passes a file at its budget", twoEffects);
36+
37+
rule.invalid(
38+
"reports only the calls past the budget, in source order",
39+
threeEffects,
40+
(output) => {
41+
assert.strictEqual(reports(output), 2);
42+
assert.include(output, "has 4 React effects against a budget of 2");
43+
assert.include(output, "src/Panel.tsx:5:");
44+
assert.include(output, "src/Panel.tsx:6:");
45+
assert.notInclude(output, "src/Panel.tsx:3:");
46+
assert.notInclude(output, "src/Panel.tsx:4:");
47+
},
48+
);
49+
50+
rule.valid(
51+
"ignores comments, strings and lookalike names",
52+
`${twoEffects}
53+
// useEffect(() => {}) in a comment
54+
/* React.useLayoutEffect(() => {}) */
55+
const label = "useEffect(() => {})";
56+
const template = \`useInsertionEffect(\${label})\`;
57+
const pipeline = Effect.matchCauseEffect(effect, {});
58+
const alias = useEffect;
59+
`,
60+
);
61+
62+
budgeted("src/New.tsx").invalid(
63+
"gives a file without an entry a budget of 0, counting member calls",
64+
`export function New() { React.useEffect(() => {}); return null; }`,
65+
(output) => {
66+
assert.strictEqual(reports(output), 1);
67+
assert.include(output, "has 1 React effect against a budget of 0");
68+
},
69+
);
70+
71+
budgeted("src/Panel.test.tsx").valid("skips test files", threeEffects);
72+
73+
budgeted("src/test/fixtures.tsx").valid("skips test directories", threeEffects);
74+
});
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import { defineRule, type ESTree } from "@oxlint/plugins";
3+
import * as Option from "effect/Option";
4+
import * as NodeFS from "node:fs";
5+
import * as NodePath from "node:path";
6+
7+
import { getPropertyName, unwrapExpression } from "../utils.ts";
8+
9+
export type EffectBudget = Readonly<Record<string, number>>;
10+
11+
export const EFFECT_BUDGET_FILE = "scripts/effect-budget.json";
12+
export const REPO_ROOT = NodePath.resolve(import.meta.dirname, "..", "..");
13+
14+
const EFFECT_HOOKS = new Set(["useEffect", "useLayoutEffect", "useInsertionEffect"]);
15+
const EFFECT_HOOK_TEXT = /use(?:Layout|Insertion)?Effect/;
16+
const UNBUDGETED_FILE = /\.test\.[cm]?[jt]sx?$|(?:^|\/)(?:test|__tests__)\//;
17+
18+
/** Matches `useEffect(...)` and member calls such as `React.useEffect(...)`. */
19+
export function isEffectHookCall(node: { readonly callee: unknown }): boolean {
20+
const callee = unwrapExpression(node.callee);
21+
if (Option.isNone(callee)) return false;
22+
const expression = callee.value;
23+
if (expression.type === "Identifier") return EFFECT_HOOKS.has(expression.name);
24+
if (expression.type === "MemberExpression" && !expression.computed) {
25+
return Option.exists(getPropertyName(expression.property), (name) => EFFECT_HOOKS.has(name));
26+
}
27+
return false;
28+
}
29+
30+
export function isBudgetedFile(repoPath: string): boolean {
31+
return !repoPath.startsWith("..") && !UNBUDGETED_FILE.test(repoPath);
32+
}
33+
34+
export function repoPathOf(root: string, fileName: string): string {
35+
return NodePath.relative(root, fileName).split(NodePath.sep).join("/");
36+
}
37+
38+
export function readEffectBudget(root: string): EffectBudget {
39+
return JSON.parse(NodeFS.readFileSync(NodePath.join(root, EFFECT_BUDGET_FILE), "utf8"));
40+
}
41+
42+
const budgets = new Map<string, EffectBudget>();
43+
const cachedBudget = (root: string): EffectBudget => {
44+
let budget = budgets.get(root);
45+
if (budget === undefined) {
46+
budget = readEffectBudget(root);
47+
budgets.set(root, budget);
48+
}
49+
return budget;
50+
};
51+
52+
const readRoot = (options: ReadonlyArray<unknown>): string => {
53+
const [first] = options;
54+
return typeof first === "object" &&
55+
first !== null &&
56+
"root" in first &&
57+
typeof first.root === "string"
58+
? first.root
59+
: REPO_ROOT;
60+
};
61+
62+
export default defineRule({
63+
meta: {
64+
type: "suggestion",
65+
docs: {
66+
description: `Hold each file to the React effect hooks it is allowed in ${EFFECT_BUDGET_FILE}; a missing entry allows none.`,
67+
},
68+
schema: [
69+
{
70+
type: "object",
71+
properties: {
72+
root: {
73+
type: "string",
74+
description: `Directory that budget keys are relative to and that holds ${EFFECT_BUDGET_FILE}. Defaults to the repository root.`,
75+
},
76+
},
77+
additionalProperties: false,
78+
},
79+
],
80+
},
81+
create(context) {
82+
const root = readRoot(context.options);
83+
const repoPath = repoPathOf(root, context.filename);
84+
if (!isBudgetedFile(repoPath) || !EFFECT_HOOK_TEXT.test(context.sourceCode.text)) return {};
85+
86+
const calls: Array<ESTree.CallExpression> = [];
87+
return {
88+
CallExpression(node) {
89+
if (isEffectHookCall(node)) calls.push(node);
90+
},
91+
"Program:exit"() {
92+
const budget = cachedBudget(root)[repoPath] ?? 0;
93+
if (calls.length <= budget) return;
94+
const message =
95+
`This file has ${calls.length} React ${calls.length === 1 ? "effect" : "effects"} against a budget of ${budget}. ` +
96+
"Prefer deriving in render, event handlers, a `key` reset, an element-owned ref callback, or a store. " +
97+
`If an effect is genuinely right, raise this file's entry in ${EFFECT_BUDGET_FILE} in the same PR.`;
98+
for (const node of calls.slice(budget)) context.report({ node, message });
99+
},
100+
};
101+
},
102+
});

‎oxlint-plugin-t3code/test/utils.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ interface RuleHarness {
5959

6060
interface RuleHarnessOptions {
6161
readonly filename?: string;
62-
readonly ruleOptions?: ReadonlyArray<unknown>;
62+
readonly ruleOptions?: ReadonlyArray<unknown> | ((fixtureDir: string) => ReadonlyArray<unknown>);
63+
/** Extra files written into the fixture directory, keyed by relative path. */
64+
readonly files?: Readonly<Record<string, string>>;
6365
}
6466

6567
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
@@ -110,11 +112,24 @@ export const createOxlintRuleHarness = (
110112
configPath,
111113
yield* encodeOxlintConfig({
112114
jsPlugins: [{ name: "t3code", specifier: pluginPath }],
113-
rules: { [ruleName]: ["error", ...(options.ruleOptions ?? [])] },
115+
rules: {
116+
[ruleName]: [
117+
"error",
118+
...(typeof options.ruleOptions === "function"
119+
? options.ruleOptions(fixtureDir)
120+
: (options.ruleOptions ?? [])),
121+
],
122+
},
114123
}),
115124
);
116-
yield* fs.makeDirectory(path.dirname(sourcePath), { recursive: true });
117-
yield* fs.writeFileString(sourcePath, source);
125+
for (const [file, contents] of [
126+
...Object.entries(options.files ?? {}),
127+
[path.relative(fixtureDir, sourcePath), source] as const,
128+
]) {
129+
const filePath = path.join(fixtureDir, file);
130+
yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
131+
yield* fs.writeFileString(filePath, contents);
132+
}
118133

119134
// Run through the current Node binary: oxlint's bin is an extensionless
120135
// shebang script, which Windows cannot spawn directly and which would

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
"tc": "vp run -r --cache --concurrency-limit 4 typecheck",
2929
"check:changed": "node scripts/check-changed.ts",
3030
"lint": "vp lint --report-unused-disable-directives",
31+
"effect-budget:update": "node scripts/effect-budget.ts",
3132
"knip": "knip --preprocessor ./scripts/knip-schemas.ts",
3233
"knip:check": "knip --include files,dependencies --no-config-hints && knip --workspace apps/server --workspace apps/desktop --workspace apps/web --workspace packages/client-runtime --workspace packages/contracts --workspace packages/effect-acp --workspace packages/effect-codex-app-server --workspace packages/shared --workspace packages/ssh --workspace packages/tailscale --workspace packages/provider-core --workspace packages/provider-acp --workspace packages/provider-acp-registry --workspace packages/provider-testing --workspace packages/provider-pi --workspace packages/provider-muse --workspace packages/provider-opencode --workspace packages/provider-cursor --workspace packages/provider-grok --workspace packages/source-control-core --workspace packages/source-control-definitions --workspace packages/source-control-azure-devops --workspace packages/source-control-bitbucket --workspace packages/source-control-forgejo --workspace packages/source-control-gitcafe --workspace packages/source-control-github --workspace packages/source-control-gitlab --workspace packages/source-control-testing --exports --preprocessor ./scripts/knip-schemas.ts --no-config-hints",
3334
"knip:production": "knip --production --preprocessor ./scripts/knip-schemas.ts",

‎pnpm-lock.yaml‎

Lines changed: 7 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)