@devries-cameron20 / t3code-1 / commits / 7f26969c51
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

chore(lint): enforce react/set-state-in-effect (#25119)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 22:01 UTC 7f26969c510eca3558f9e4f8f9a8fb4acb41f564
25 files changed +118 -25
apps/mobile/src/components/MediaVideoPlayer.tsx
+1
@@ -91,6 +91,7 @@ function LoadedMediaVideo(props: {
91
92 useEffect(() => {
93 const controller = new AbortController();
94 + // oxlint-disable-next-line react/set-state-in-effect -- Starting a native media load publishes pending before its async result.
95 setLoadState("pending");
96 // A renewed signature is used on Retry, not as a reason to reset the native player.
97 void loadSource(controller.signal).then(
apps/mobile/src/components/ProjectFavicon.tsx
+1
@@ -168,6 +168,7 @@ function ProjectFaviconImage(props: {
168 if (faviconRequest === null) return;
169
170 const endRequest = beginProjectFaviconRequest(faviconRequest);
171 + // oxlint-disable-next-line react/set-state-in-effect -- Publishes the favicon request registered with the external loader until its cleanup runs.
172 setActiveFaviconRequest(faviconRequest);
173 return endRequest;
174 }, [faviconRequest]);
apps/mobile/src/components/VideoPreviewModal.ios.tsx
+1
@@ -70,6 +70,7 @@ function NativeVideoPreview(props: {
70 return () => fullscreenVideoClosed();
71 }, []);
72 useEffect(() => {
73 + // oxlint-disable-next-line react/set-state-in-effect -- The native player latches the first resolved URL to keep its playback session.
74 if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);
75 }, [playbackUrl, resolvedUrl]);
76 useEffect(() => {
apps/mobile/src/components/VideoPreviewModal.tsx
+1
@@ -64,6 +64,7 @@ function useLocalPlayback(source: LocalVideoPreviewSource): PlaybackState {
64 );
65 const { id: attachmentId, fileUri } = attachment;
66 useEffect(() => {
67 + // oxlint-disable-next-line react/set-state-in-effect -- A new attachment clears the previous attachment's result before loading.
68 setUri(null);
69 setError(null);
70 const controller = new AbortController();
apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+3
@@ -77,6 +77,7 @@ export function ConnectionsNewRouteScreen({
77
78 useEffect(() => {
79 const { host, code } = parsePairingUrl(connectionPairingUrl);
80 + // oxlint-disable-next-line react/set-state-in-effect -- A new pairing URL reseeds the editable host and code fields.
81 setHostInput(host);
82 setCodeInput(code);
83 }, [connectionPairingUrl]);
@@ -87,12 +88,14 @@ export function ConnectionsNewRouteScreen({
88 }
89
90 const { host, code } = parsePairingUrl(routePairingUrl);
91 + // oxlint-disable-next-line react/set-state-in-effect -- A pairing URL from the route reseeds the editable host and code fields.
92 setHostInput(host);
93 setCodeInput(code);
94 }, [routePairingUrl]);
95
96 useEffect(() => {
97 if (pairingConnectionError) {
98 + // oxlint-disable-next-line react/set-state-in-effect -- A pairing failure reported by the connection runtime ends the submit.
99 setIsSubmitting(false);
100 }
101 }, [pairingConnectionError]);
apps/mobile/src/features/files/FileTreeBrowser.tsx
+1
@@ -153,6 +153,7 @@ export function FileTreeBrowser(props: {
153 if (!controlledSelectedPath) {
154 return;
155 }
156 + // oxlint-disable-next-line react/set-state-in-effect -- An externally selected file expands its ancestor folders; the user can collapse them afterwards.
157 setExpandedPaths((current) => {
158 const ancestors = ancestorPaths(controlledSelectedPath);
159 if (ancestors.every((ancestor) => current.has(ancestor))) {
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+1
@@ -387,6 +387,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
387 if (!guidesEnabled && section === "guide") {
388 requestedSection.current = "overview";
389 currentScrollOffset.current = scrollOffsets.current.overview ?? -insets.top;
390 + // oxlint-disable-next-line react/set-state-in-effect -- When guides turn off, the tab and its saved scroll offset must switch to overview together.
391 setSection("overview");
392 }
393 }, [guidesEnabled, section, insets.top, currentScrollOffset, requestedSection, scrollOffsets]);
apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts
+1
@@ -59,6 +59,7 @@ export function useNativeReviewDiffHighlighting(input: {
59 const previousRange = scheduler.reset();
60 highlightedRowIdsRef.current = new Set();
61 pendingPatchesRef.current = [];
62 + // oxlint-disable-next-line react/set-state-in-effect -- Resetting the native highlighter clears the viewport and token-patch snapshots together.
63 setViewport({ scope: viewportScope, range: null });
64 setTokensPatchJson(createEmptyTokenPatch(resetKey));
65 // A token reset need not produce another native range event. Reuse only an
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+2
@@ -116,6 +116,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
116 };
117
118 useEffect(() => {
119 + // oxlint-disable-next-line react/set-state-in-effect -- Reads native notification permission on mount and on every foreground.
120 void refreshNotifications();
121 const subscription = AppState.addEventListener("change", (state) => {
122 if (state === "active") void refreshNotifications();
@@ -125,6 +126,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
126
127 useEffect(() => {
128 if (!isLoaded) {
129 + // oxlint-disable-next-line react/set-state-in-effect -- Live Activity status shows checking until stored preferences load.
130 setLiveActivityStatus("checking");
131 return;
132 }
apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx
+2
@@ -121,6 +121,7 @@ function EnabledShowcaseCaptureCoordinator(props: { readonly pathname: string })
121 if (orientationSettled) return;
122 const orientation = getNativeShowcaseOrientation();
123 if (orientation === null) {
124 + // oxlint-disable-next-line react/set-state-in-effect -- Capture readiness follows the native orientation change.
125 setOrientationSettled(true);
126 return;
127 }
@@ -295,6 +296,7 @@ function EnabledShowcaseCaptureCoordinator(props: { readonly pathname: string })
296 (scene === "agent-activity" && !agentActivityStaged) ||
297 !isShowcaseNativeContentReady({ scene, themeId, renderSignal })
298 ) {
299 + // oxlint-disable-next-line react/set-state-in-effect -- Capture readiness clears while the scene, fixture, or native content is not ready.
300 setReadyScene(null);
301 return;
302 }
apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+2
@@ -37,6 +37,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
37 const [initialized, setInitialized] = useState(false);
38 useLayoutEffect(() => {
39 reset();
40 + // oxlint-disable-next-line react/set-state-in-effect -- Draft reset runs once before first paint; initialized gates the screen until then.
41 setInitialized(true);
42 }, [reset]);
43 const pendingTaskId = Array.isArray(params.pendingTaskId)
@@ -90,6 +91,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
91 if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
92 const branchName = initialProjectRef.branch;
93 let active = true;
94 + // oxlint-disable-next-line react/set-state-in-effect -- Counts the serialized Git checkout this effect starts.
95 setPendingCheckouts((count) => count + 1);
96 // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
97 checkoutTail.current = checkoutTail.current.then(async () => {
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+3
@@ -355,6 +355,7 @@ export function NewTaskDraftScreen(props: {
355 return;
356 }
357 if (requestedInitialProjectAvailable) {
358 + // oxlint-disable-next-line react/set-state-in-effect -- Ends the return-to-picker flow once the requested project arrives from the catalog.
359 setIsReturningToProjectPicker(false);
360 return;
361 }
@@ -493,6 +494,7 @@ export function NewTaskDraftScreen(props: {
494 }
495
496 if (projects.length > 0) {
497 + // oxlint-disable-next-line react/set-state-in-effect -- Route-driven project resolution starts the return-to-picker flow when no project matches.
498 setIsReturningToProjectPicker(true);
499 }
500 return;
@@ -595,6 +597,7 @@ export function NewTaskDraftScreen(props: {
597 let didConsumeShare = false;
598 let needsDraftRestore = false;
599 activeShareImportTokenRef.current = importToken;
600 + // oxlint-disable-next-line react/set-state-in-effect -- Publishes the share import started by this effect before its async work runs.
601 setImportingShareKey(importKey);
602 void (async () => {
603 await reserveShare(shareId, {
apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
+1 -1
@@ -288,7 +288,7 @@ export function ThreadArrangementSheet(props: { onClose: () => void }) {
288 .map((row) => `${row.key}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`)
289 .join("|");
290 useEffect(() => {
291 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A changed thread order cancels the in-progress drag; stop only touches refs and state setters.
291 + // oxlint-disable-next-line react/exhaustive-effect-dependencies, react/set-state-in-effect -- A changed thread order cancels the in-progress drag and clears its preview; stop only touches refs and state setters.
292 stop();
293 }, [orderVersion]);
294 useEffect(
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+1
@@ -421,6 +421,7 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
421 };
422 }, []);
423 useEffect(() => {
424 + // oxlint-disable-next-line react/set-state-in-effect -- Any native keyboard report clears the suspect flag set when the app resumed.
425 setKeyboardStateSuspect(false);
426 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Any keyboard visibility or height report clears the suspect flag set when the app resumed.
427 }, [isKeyboardVisible, liveKeyboardHeight]);
apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx new
+66
@@ -0,0 +1,66 @@
1 +import type { ReactNode } from "react";
2 +import { act } from "react";
3 +import { createRoot } from "react-dom/client";
4 +import { expect, it, vi } from "vite-plus/test";
5 +
6 +const harness = vi.hoisted(() => ({
7 + failImage: () => {},
8 + Passthrough: ({ children }: { children?: unknown }) => children,
9 +}));
10 +
11 +vi.mock("react-native", () => ({
12 + Pressable: harness.Passthrough,
13 + StyleSheet: { absoluteFill: {} },
14 + View: harness.Passthrough,
15 +}));
16 +vi.mock("expo-image", () => ({
17 + Image: (props: { onError: () => void }) => {
18 + harness.failImage = props.onError;
19 + return <img alt="" />;
20 + },
21 +}));
22 +vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));
23 +vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null }));
24 +vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" }));
25 +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
26 +vi.mock("../../components/FilePreviewGallery", () => ({
27 + useFilePreviewGallery: () => (source: unknown) => source,
28 +}));
29 +vi.mock("../../components/ui/AppText", () => ({
30 + AppText: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
31 +}));
32 +vi.mock("../../components/MediaActionsMenu", () => ({ MediaActionsMenu: harness.Passthrough }));
33 +vi.mock("../../components/ui/NativePresentation", () => ({
34 + PresentationSource: harness.Passthrough,
35 +}));
36 +vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) }));
37 +vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() }));
38 +
39 +import { ThreadMarkdownImageView } from "./ThreadMarkdownImage";
40 +
41 +it("retries a failed image once its URI comes back through null", async () => {
42 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
43 + const container = document.createElement("div");
44 + const root = createRoot(container);
45 + const view = (uri: string | null) => (
46 + <ThreadMarkdownImageView
47 + uri={uri}
48 + sourceKey="attachment:a"
49 + unavailable={false}
50 + alt={null}
51 + onPressPreview={() => {}}
52 + />
53 + );
54 + try {
55 + await act(async () => root.render(view("https://example.test/a.png")));
56 + await act(async () => harness.failImage());
57 + expect(container.textContent).toContain("Image unavailable");
58 +
59 + await act(async () => root.render(view(null)));
60 + await act(async () => root.render(view("https://example.test/a.png")));
61 + expect(container.textContent).not.toContain("Image unavailable");
62 + expect(container.querySelector("img")).not.toBeNull();
63 + } finally {
64 + await act(async () => root.unmount());
65 + }
66 +});
apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+13 -15
@@ -45,18 +45,15 @@ export function ThreadMarkdownImageView(props: {
45 measuredWidth > 0 && contextWidth > 0
46 ? Math.min(contextWidth, measuredWidth)
47 : contextWidth || measuredWidth;
48 - const [decodedSize, setDecodedSize] = useState<{ width: number; height: number } | null>(null);
49 - const [failedUri, setFailedUri] = useState<string | null>(null);
50 -
51 - useEffect(() => {
52 - setDecodedSize(null);
53 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new source invalidates the decoded image dimensions.
54 - }, [props.sourceKey]);
55 -
56 - useEffect(() => {
57 - setFailedUri(null);
58 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new image URI clears the previous load failure.
59 - }, [props.uri]);
48 + // Keyed by source so a new source drops the previous image's decoded dimensions.
49 + const [decoded, setDecoded] = useState<{
50 + sourceKey: string;
51 + size: { width: number; height: number };
52 + } | null>(null);
53 + const decodedSize = decoded?.sourceKey === props.sourceKey ? decoded.size : null;
54 + // A failure belongs to one URI; any URI change, including through null, retries.
55 + const [failure, setFailure] = useState({ uri: props.uri, failed: false });
56 + if (failure.uri !== props.uri) setFailure({ uri: props.uri, failed: false });
57
58 const sourceSize = decodedSize ?? props.knownSize ?? null;
59 const displaySize: MarkdownImageDisplaySize | null =
@@ -67,7 +64,8 @@ export function ThreadMarkdownImageView(props: {
64 sourceHeight: sourceSize.height,
65 availableWidth,
66 });
70 - const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);
67 + const failed =
68 + props.unavailable || (props.uri !== null && failure.uri === props.uri && failure.failed);
69 const placeholderWidth: ViewStyle["width"] =
70 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
71 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
@@ -129,8 +127,8 @@ export function ThreadMarkdownImageView(props: {
127 key={props.sourceKey}
128 uri={props.uri}
129 format={props.format}
132 - onLoad={setDecodedSize}
133 - onError={() => setFailedUri(props.uri)}
130 + onLoad={(size) => setDecoded({ sourceKey: props.sourceKey, size })}
131 + onError={() => setFailure({ uri: props.uri, failed: true })}
132 />
133 </View>
134 </Pressable>
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+1
@@ -274,6 +274,7 @@ function ThreadNavigationSidebarPane(
274 const nowMinute = now.slice(0, 16);
275 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
276 useEffect(() => {
277 + // oxlint-disable-next-line react/set-state-in-effect -- Refreshes the minute clock when the minute interval starts.
278 setNow(new Date().toISOString());
279 const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
280 return () => clearInterval(id);
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+1
@@ -431,6 +431,7 @@ function ThreadRouteContent(
431 ]);
432
433 useEffect(() => {
434 + // oxlint-disable-next-line react/set-state-in-effect -- Inspector selection follows route ownership but keeps an inspector the user opened.
435 setInspectorSelection((current) => {
436 if (props.renderInspector === undefined) {
437 if (current === null || current.mode === "route") {
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+1
@@ -418,6 +418,7 @@ export function NewTaskFlowProvider(
418 ) {
419 return;
420 }
421 + // oxlint-disable-next-line react/set-state-in-effect -- Creates the persistent draft once the project selection is ready; the key must exist before the composer mounts.
422 setActiveDraftKey(
423 createNewTaskDraft({
424 environmentId: selectedProject.environmentId,
apps/mobile/src/features/threads/thread-inspector-content-stack.tsx
+1
@@ -58,6 +58,7 @@ export function ThreadInspectorContentStack(props: {
58 );
59
60 useEffect(() => {
61 + // oxlint-disable-next-line react/set-state-in-effect -- Keeps opened inspector views mounted so UIKit keeps their focus and scroll.
62 setMountedModes((current) => {
63 if (current.has(props.mode)) {
64 return current;
apps/mobile/src/features/threads/use-composer-command-menu.ts
+2
@@ -220,6 +220,7 @@ export function useComposerCommandMenu({
220 useEffect(() => {
221 const inserted = ownerKey ? readComposerDraftSelection(ownerKey, draftMessage) : null;
222 if (inserted) {
223 + // oxlint-disable-next-line react/set-state-in-effect -- Applies a selection inserted into the draft store by another surface.
224 setSelection((current) =>
225 current.start === inserted.start && current.end === inserted.end ? current : inserted,
226 );
@@ -301,6 +302,7 @@ export function useComposerCommandMenu({
302 )
303 return;
304 if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, projectCwd, now)) {
305 + // oxlint-disable-next-line react/set-state-in-effect -- A current provider workspace snapshot clears the pending refresh retry.
306 setWorkspaceRefreshRetry(null);
307 return;
308 }
apps/mobile/src/features/threads/use-worktree-setup.ts
+1
@@ -27,6 +27,7 @@ export function useWorktreeSetup(input: {
27 );
28 const snapshot = resolveWorktreeSetupSnapshot(input.threadId, query.data, live);
29 useEffect(() => {
30 + // oxlint-disable-next-line react/set-state-in-effect -- Holds the last setup snapshot while the live subscription changes over.
31 if (snapshot && snapshot !== live) setHeld({ key, snapshot });
32 }, [key, live, snapshot]);
33 return {
apps/mobile/src/state/use-vcs-action-state.ts
+9 -9
@@ -1,7 +1,8 @@
1 import { useAtomValue } from "@effect/atom-react";
2 +import { secondTick } from "@t3tools/client-runtime/clock";
3 import { type VcsActionState, type VcsActionTarget } from "@t3tools/client-runtime/state/vcs";
4 import { Atom } from "effect/reactivity";
4 -import { useEffect, useState } from "react";
5 +import { useSyncExternalStore } from "react";
6
7 import { appAtomRegistry } from "./atom-registry";
8 import { vcsActionManager } from "./vcs";
@@ -61,6 +62,8 @@ export interface GitActionProgress {
62 readonly prUrl?: string;
63 }
64
65 +const subscribeNever = () => () => {};
66 +
67 const EMPTY_PROGRESS: GitActionProgress = {
68 phase: "idle",
69 label: null,
@@ -78,14 +81,11 @@ export function useGitActionProgress(target: VcsActionTarget): GitActionProgress
81 const actionState = useVcsActionState(target);
82 const { result } = useGitActionResultNotification();
83
81 - // Keep clock state; the compiler caches render-time Date.now() and would freeze the label.
82 - const [nowMs, setNowMs] = useState(() => Date.now());
83 - useEffect(() => {
84 - if (!actionState.isRunning) return;
85 - setNowMs(Date.now());
86 - const interval = setInterval(() => setNowMs(Date.now()), 1000);
87 - return () => clearInterval(interval);
88 - }, [actionState.isRunning]);
84 + // Only a running action shows elapsed time, so only it subscribes to the second tick.
85 + const nowMs = useSyncExternalStore(
86 + actionState.isRunning ? secondTick.subscribe : subscribeNever,
87 + secondTick.getSnapshot,
88 + );
89
90 if (actionState.isRunning) {
91 const description =
apps/mobile/vite.config.ts
+1
@@ -10,6 +10,7 @@ const reactTests = [
10 "src/components/ui/Dialog.android.test.tsx",
11 "src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
12 "src/features/settings/components/BranchNamingSettings.test.tsx",
13 + "src/features/threads/ThreadMarkdownImage.test.tsx",
14 "src/features/threads/UsageLimitRecoveryCard.test.tsx",
15 "src/native/NativeHeaderToolbar.test.tsx",
16 "src/native/useRestingTopOffset.test.tsx",
vite.config.ts
+1
@@ -230,6 +230,7 @@ export default defineConfig({
230 "react/purity": "error",
231 "react/refs": "error",
232 "react/exhaustive-effect-dependencies": "error",
233 + "react/set-state-in-effect": "error",
234 "react/immutability": "error",
235 "react/no-array-index-key": "error",
236 "react/no-unstable-nested-components": "error",