The best way to control Claude Code, Codex and more from any computer or phone
refactor(mobile): shared AppState, reduce-motion and back-button helpers (#25011)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 18:13 UTC
c8c6deb6139a4dfb0ef353a003aa8d19761b720f
10 files changed
+181
-89
apps/mobile/src/components/ui/AppBar.android.tsx
+7
-17
@@ -1,12 +1,6 @@
1
-import { useCallback, useEffect, useRef, useState } from "react";
2
-import {
3
- BackHandler,
4
- Keyboard,
5
- Pressable,
6
- TextInput,
7
- type TextInputInstance,
8
- View,
9
-} from "react-native";
1
+import { useCallback, useRef, useState } from "react";
2
+import { Keyboard, Pressable, TextInput, type TextInputInstance, View } from "react-native";
3
+import { useHardwareBack } from "../../lib/backHandler";
4
import { useToolbarLayout } from "./useToolbarLayout";
5
import { NativeStackScreenOptions } from "../../native/StackHeader";
6
import { AndroidWorkspaceSidebarButton } from "../../features/layout/workspace-sidebar-toolbar";
@@ -34,14 +28,10 @@ export function AppBar(props: AppBarProps) {
28
setSearchOpen(false);
29
Keyboard.dismiss();
30
}, [onSearchChange]);
37
- useEffect(() => {
38
- if (!searching || search?.mode === "inline") return;
39
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
40
- closeSearch();
41
- return true;
42
- });
43
- return () => subscription.remove();
44
- }, [closeSearch, searching, search?.mode]);
31
+ useHardwareBack(searching && search?.mode !== "inline", () => {
32
+ closeSearch();
33
+ return true;
34
+ });
35
const menuView = props.menus?.map((menu) => (
36
<Menu
37
key={menu.title}
apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
+3
-8
@@ -7,10 +7,11 @@ import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/c
7
import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
8
import * as Option from "effect/Option";
9
import { useCallback, useEffect, useRef, useState } from "react";
10
-import { AppState, Platform, TextInput, View } from "react-native";
10
+import { Platform, TextInput, View } from "react-native";
11
import { useSafeAreaInsets } from "react-native-safe-area-context";
12
13
import { ControlPill } from "../../components/ui/ControlPill";
14
+import { useAppForeground } from "../../lib/appState";
15
import { AppBar } from "../../components/ui/AppBar";
16
17
import { useThreadServerBrowserTabs } from "../../state/preview";
@@ -79,7 +80,7 @@ function BrowserPreviewScreen({
80
const prepared = usePreparedConnection(environmentId);
81
const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
82
const focused = useIsFocused();
82
- const [foreground, setForeground] = useState(AppState.currentState !== "background");
83
+ const foreground = useAppForeground();
84
const [selectedTabId, setSelectedTabId] = useState(initialTabId);
85
const [pictureInPicture, setPictureInPicture] = useState(NO_PICTURE_IN_PICTURE);
86
const [streaming, setStreaming] = useState(false);
@@ -94,12 +95,6 @@ function BrowserPreviewScreen({
95
setPictureInPicture(NO_PICTURE_IN_PICTURE);
96
setSelectedTabId(tabId);
97
}
97
- useEffect(() => {
98
- const subscription = AppState.addEventListener("change", (state) =>
99
- setForeground(state !== "background"),
100
- );
101
- return () => subscription.remove();
102
- }, []);
98
useEffect(() => {
99
if (focused && loaded && tabs.length === 0) onClose();
100
}, [focused, loaded, tabs.length, onClose]);
apps/mobile/src/features/browser/ThreadBrowserFloat.tsx
+3
-8
@@ -3,10 +3,11 @@ import type { EnvironmentId, PreviewSessionSnapshot, ThreadId } from "@t3tools/c
3
import { previewPdfAssetUrl } from "@t3tools/shared/preview";
4
import * as Option from "effect/Option";
5
import { useCallback, useEffect, useRef, useState } from "react";
6
-import { AppState, Pressable, View } from "react-native";
6
+import { Pressable, View } from "react-native";
7
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
8
9
import { SymbolView } from "../../components/ui/AppSymbol";
10
+import { useAppForeground } from "../../lib/appState";
11
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
12
import { browserTabTitle } from "./browserTabs";
13
import { PreviewStreamWebView } from "./PreviewStreamWebView";
@@ -41,13 +42,7 @@ export function ThreadBrowserFloat(props: {
42
if (opened !== undefined) setTabId(opened.tabId);
43
}, [props.loaded, props.tabs]);
44
const focused = useIsFocused();
44
- const [foreground, setForeground] = useState(AppState.currentState !== "background");
45
- useEffect(() => {
46
- const subscription = AppState.addEventListener("change", (state) =>
47
- setForeground(state !== "background"),
48
- );
49
- return () => subscription.remove();
50
- }, []);
45
+ const foreground = useAppForeground();
46
const tab = props.tabs.find((entry) => entry.tabId === tabId) ?? null;
47
const onOpen = props.onOpen;
48
const open = useCallback(() => {
apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
+8
-16
@@ -12,7 +12,7 @@ import * as Cause from "effect/Cause";
12
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
13
import * as Haptics from "expo-haptics";
14
import { Accelerometer } from "expo-sensors";
15
-import { AppState, BackHandler, Pressable, StatusBar, View } from "react-native";
15
+import { Pressable, StatusBar, View } from "react-native";
16
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
17
import { useSafeAreaInsets } from "react-native-safe-area-context";
18
@@ -27,6 +27,8 @@ import {
27
findHeaderMenuAction,
28
} from "../../components/ui/headerMenu.android";
29
import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
30
+import { useAppForeground } from "../../lib/appState";
31
+import { useHardwareBack } from "../../lib/backHandler";
32
import { deriveBottomControlInsets } from "../../lib/reserved-regions";
33
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
34
import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
@@ -88,7 +90,7 @@ export function DevicePreviewScreen({
90
const handleBounds = deriveBottomControlInsets(useNativeColumnLayoutMetrics());
91
const { themeVariables } = useAppearancePreferences();
92
const focused = useIsFocused();
91
- const [foreground, setForeground] = useState(AppState.currentState !== "background");
93
+ const foreground = useAppForeground();
94
const [selectedKey, setSelectedKey] = useState<string | null>(initialDeviceKey ?? null);
95
const [inputConnected, setInputConnected] = useState(false);
96
const [streamAttempt, setStreamAttempt] = useState(0);
@@ -107,12 +109,6 @@ export function DevicePreviewScreen({
109
},
110
[embedded],
111
);
110
- useEffect(() => {
111
- const subscription = AppState.addEventListener("change", (state) =>
112
- setForeground(state !== "background"),
113
- );
114
- return () => subscription.remove();
115
- }, []);
112
useEffect(() => {
113
if (focused && state.data !== null && previews.length === 0) onClose();
114
}, [focused, state.data, previews.length, onClose]);
@@ -127,14 +123,10 @@ export function DevicePreviewScreen({
123
});
124
return () => subscription.remove();
125
}, [focused, foreground, embedded]);
130
- useEffect(() => {
131
- if (controlsVisible) return;
132
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
133
- setControlsVisible(true);
134
- return true;
135
- });
136
- return () => subscription.remove();
137
- }, [controlsVisible]);
126
+ useHardwareBack(!controlsVisible, () => {
127
+ setControlsVisible(true);
128
+ return true;
129
+ });
130
131
const shutDownDevice = async () => {
132
if (!preview || shuttingDown) return;
apps/mobile/src/features/files/FilesHeader.tsx
+7
-10
@@ -1,5 +1,5 @@
1
-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
2
-import { BackHandler, Keyboard, type TextInputInstance, View } from "react-native";
1
+import { useCallback, useRef, useState, type ReactNode } from "react";
2
+import { Keyboard, type TextInputInstance, View } from "react-native";
3
4
import {
5
AndroidHeaderIconButton,
@@ -8,6 +8,7 @@ import {
8
import { AndroidAnchoredMenu } from "../../components/ui/AndroidAnchoredMenu";
9
import { SearchField } from "../../components/ui/SearchField";
10
import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
11
+import { useHardwareBack } from "../../lib/backHandler";
12
13
export function FilesHeader(props: {
14
readonly projectName: string;
@@ -28,14 +29,10 @@ export function FilesHeader(props: {
29
Keyboard.dismiss();
30
}, [onSearchQueryChange]);
31
31
- useEffect(() => {
32
- if (!searching) return;
33
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
34
- closeSearch();
35
- return true;
36
- });
37
- return () => subscription.remove();
38
- }, [closeSearch, searching]);
32
+ useHardwareBack(searching, () => {
33
+ closeSearch();
34
+ return true;
35
+ });
36
37
return (
38
<View>
apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
+7
-10
@@ -1,5 +1,5 @@
1
-import { useEffect, useState } from "react";
2
-import { BackHandler, Platform, View } from "react-native";
1
+import { useState } from "react";
2
+import { Platform, View } from "react-native";
3
import { WebView } from "react-native-webview";
4
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
5
@@ -9,6 +9,7 @@ import { FilePreviewLoading } from "./FilePreviewFeedback";
9
import { LoadingStrip } from "../../components/ui/LoadingStrip";
10
import { PdfPreview } from "../../components/PdfPreview";
11
import { ControlPill } from "../../components/ui/ControlPill";
12
+import { useHardwareBack } from "../../lib/backHandler";
13
import { isPdfPreviewUri } from "../../lib/pdfPreview";
14
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
15
@@ -27,14 +28,10 @@ function DocumentWebPreview(props: { readonly uri: string }) {
28
const [loadError, setLoadError] = useState<string | null>(null);
29
const [linkedPdf, setLinkedPdf] = useState<string | null>(null);
30
30
- useEffect(() => {
31
- if (linkedPdf === null) return;
32
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
33
- setLinkedPdf(null);
34
- return true;
35
- });
36
- return () => subscription.remove();
37
- }, [linkedPdf]);
31
+ useHardwareBack(linkedPdf !== null, () => {
32
+ setLinkedPdf(null);
33
+ return true;
34
+ });
35
36
if (isPdfPreviewUri(props.uri)) {
37
return (
apps/mobile/src/features/threads/thread-work-log.tsx
+3
-20
@@ -33,9 +33,7 @@ import {
33
type ReactNode,
34
} from "react";
35
import {
36
- AccessibilityInfo,
36
Animated as NativeAnimated,
38
- AppState,
37
type ColorValue,
38
Easing,
39
Pressable,
@@ -63,6 +61,7 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
61
import { AppText as Text } from "../../components/ui/AppText";
62
import { T3Wordmark } from "../../components/T3Wordmark";
63
import { BrowserAppIcon } from "./BrowserAppIcon";
64
+import { useAppActive, useReduceMotionEnabled } from "../../lib/appState";
65
import { cn } from "../../lib/cn";
66
import { THREAD_WORK_ROW_MIN_HEIGHT, type deriveThreadWorkLogSizing } from "../../lib/layout";
67
import {
@@ -264,8 +263,8 @@ export function ShimmeringWorkContent(props: {
263
}) {
264
const [availableWidth, setAvailableWidth] = useState(0);
265
const [textWidth, setTextWidth] = useState(0);
267
- const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
268
- const [reducedMotion, setReducedMotion] = useState(true);
266
+ const appIsActive = useAppActive();
267
+ const reducedMotion = useReduceMotionEnabled();
268
const screenIsFocused = useIsFocused();
269
const progress = useAnimatedValue(0);
270
const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
@@ -274,22 +273,6 @@ export function ShimmeringWorkContent(props: {
273
(props.showIcon ? SHIMMER_ICON_AND_GAP_WIDTH : 0) + Math.ceil(textWidth),
274
);
275
277
- useEffect(() => {
278
- const subscription = AppState.addEventListener("change", (state) => {
279
- setAppIsActive(state === "active");
280
- });
281
- return () => subscription.remove();
282
- }, []);
283
-
284
- useEffect(() => {
285
- void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
286
- const subscription = AccessibilityInfo.addEventListener(
287
- "reduceMotionChanged",
288
- setReducedMotion,
289
- );
290
- return () => subscription.remove();
291
- }, []);
292
-
276
// Runs on React Native's native driver instead of Reanimated, whose
277
// per-frame commits starve React's while commit pausing is disabled
278
// (package.json). See docs/internals/performance-regressions.md.
apps/mobile/src/lib/appState.test.ts
new
+45
@@ -0,0 +1,45 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+
3
+const native = vi.hoisted(() => ({
4
+ enabled: false,
5
+ listeners: new Set<(enabled: boolean) => void>(),
6
+}));
7
+
8
+vi.mock("react-native", () => ({
9
+ AppState: { currentState: "active", addEventListener: vi.fn() },
10
+ AccessibilityInfo: {
11
+ addEventListener: (_event: string, listener: (enabled: boolean) => void) => {
12
+ native.listeners.add(listener);
13
+ return { remove: () => native.listeners.delete(listener) };
14
+ },
15
+ isReduceMotionEnabled: () => Promise.resolve(native.enabled),
16
+ },
17
+}));
18
+
19
+import { readReduceMotionEnabled, subscribeReduceMotion } from "./appState";
20
+
21
+describe("reduce motion store", () => {
22
+ it("reseeds from native after observation stops and restarts", async () => {
23
+ native.enabled = false;
24
+ const unsubscribe = subscribeReduceMotion(() => undefined);
25
+ await Promise.resolve();
26
+ expect(readReduceMotionEnabled()).toBe(false);
27
+ unsubscribe();
28
+
29
+ // Changed while nobody listened: no event reaches the store.
30
+ native.enabled = true;
31
+ const unsubscribeAgain = subscribeReduceMotion(() => undefined);
32
+ // Unknown until the reseed lands, which reads as reduced, not the stale false.
33
+ expect(readReduceMotionEnabled()).toBe(true);
34
+ await Promise.resolve();
35
+ expect(readReduceMotionEnabled()).toBe(true);
36
+ unsubscribeAgain();
37
+ });
38
+
39
+ it("ignores a seed that resolves after the last unsubscribe", async () => {
40
+ native.enabled = false;
41
+ subscribeReduceMotion(() => undefined)();
42
+ await Promise.resolve();
43
+ expect(readReduceMotionEnabled()).toBe(true);
44
+ });
45
+});
apps/mobile/src/lib/appState.ts
new
+79
@@ -0,0 +1,79 @@
1
+import { useSyncExternalStore } from "react";
2
+import { AccessibilityInfo, AppState } from "react-native";
3
+
4
+type Listener = () => void;
5
+
6
+function subscribeAppState(onChange: Listener): () => void {
7
+ const subscription = AppState.addEventListener("change", () => onChange());
8
+ return () => subscription.remove();
9
+}
10
+
11
+function isAppActive(): boolean {
12
+ return AppState.currentState === "active";
13
+}
14
+
15
+export function useAppActive(): boolean {
16
+ return useSyncExternalStore(subscribeAppState, isAppActive);
17
+}
18
+
19
+function isAppForeground(): boolean {
20
+ return AppState.currentState !== "background";
21
+}
22
+
23
+/**
24
+ * True unless the app is backgrounded. Unlike useAppActive, the transient
25
+ * "inactive" state (Control Center, the app switcher, a system prompt) still
26
+ * counts as foreground, so live streams do not reconnect around it.
27
+ */
28
+export function useAppForeground(): boolean {
29
+ return useSyncExternalStore(subscribeAppState, isAppForeground);
30
+}
31
+
32
+// Null until the native seed resolves; read as reduced so animated consumers
33
+// never start motion a reduce-motion user has turned off.
34
+let reduceMotionEnabled: boolean | null = null;
35
+const reduceMotionListeners = new Set<Listener>();
36
+let reduceMotionSubscription: { remove: () => void } | null = null;
37
+
38
+function setReduceMotionEnabled(next: boolean) {
39
+ if (next === reduceMotionEnabled) return;
40
+ reduceMotionEnabled = next;
41
+ for (const listener of reduceMotionListeners) listener();
42
+}
43
+
44
+export function subscribeReduceMotion(onChange: Listener): () => void {
45
+ reduceMotionListeners.add(onChange);
46
+ if (reduceMotionSubscription === null) {
47
+ const subscription = AccessibilityInfo.addEventListener(
48
+ "reduceMotionChanged",
49
+ setReduceMotionEnabled,
50
+ );
51
+ reduceMotionSubscription = subscription;
52
+ // The native event only reports changes; seed the current value once per
53
+ // observation, and drop a seed that resolves after observation stopped.
54
+ void AccessibilityInfo.isReduceMotionEnabled().then(
55
+ (enabled) => {
56
+ if (reduceMotionSubscription === subscription) setReduceMotionEnabled(enabled);
57
+ },
58
+ () => undefined,
59
+ );
60
+ }
61
+ return () => {
62
+ reduceMotionListeners.delete(onChange);
63
+ if (reduceMotionListeners.size === 0) {
64
+ reduceMotionSubscription?.remove();
65
+ reduceMotionSubscription = null;
66
+ // Changes made while nobody observed were never reported, so the cached
67
+ // value can be stale; the next subscriber reseeds from native.
68
+ reduceMotionEnabled = null;
69
+ }
70
+ };
71
+}
72
+
73
+export function readReduceMotionEnabled(): boolean {
74
+ return reduceMotionEnabled ?? true;
75
+}
76
+
77
+export function useReduceMotionEnabled(): boolean {
78
+ return useSyncExternalStore(subscribeReduceMotion, readReduceMotionEnabled);
79
+}
apps/mobile/src/lib/backHandler.ts
new
+19
@@ -0,0 +1,19 @@
1
+import { useIsFocused } from "@react-navigation/native";
2
+import { useEffect, useEffectEvent } from "react";
3
+import { BackHandler } from "react-native";
4
+
5
+/**
6
+ * Android hardware back while `active` and the owning screen is focused.
7
+ * Keyed on those alone, not `onBack`: BackHandler calls the newest listener
8
+ * first, so re-registering per render lets a covered screen consume Back.
9
+ */
10
+export function useHardwareBack(active: boolean, onBack: () => boolean) {
11
+ const focused = useIsFocused();
12
+ const handleBack = useEffectEvent(onBack);
13
+ // oxlint-disable-next-line t3code/react-effect-budget -- subscribes to BackHandler for the focused screen's lifetime
14
+ useEffect(() => {
15
+ if (!active || !focused) return;
16
+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => handleBack());
17
+ return () => subscription.remove();
18
+ }, [active, focused]);
19
+}