Skip to content

Commit c35eee2

Browse files
fix(react): stabilize useQuery thunk identity across re-renders (#33)
* fix(react): stabilize useQuery thunk identity across re-renders Previously the thunk passed to signalium's useReactive was a fresh inline arrow per call. The Signalium Babel preset wrapped it in useCallback(fn, [QueryClass, args]), but args is the rest collection, a fresh array literal per call, so Object.is dep comparison always returned false and useCallback returned a new fn every render. Each render created a new ReactiveDefinition and signal in the scope. Under React commit orderings where the microtask flush straddles useSyncExternalStore's unsubscribe-old and subscribe-new (React 18 / React Native concurrent rendering), Signalium's cancelDeactivate rescue could fail. The query's relay then lost its sole watcher to a deactivate cascade and a consumer that was still mounted observed a spurious getConfig.subscribe cleanup. Wrap the thunk in useMemo keyed on [QueryClass, hashValue(args)] so the same fn is reused across renders with deeply-equal args. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix lint issues * chore(react): trim verbose comments in useQuery Collapse the debug-counter JSDoc and the WHY block in useQuery to keep only the load-bearing context for future readers (why useMemo + hash, what breaks without it). Behavior unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(react): further trim useQuery comments Drop the Babel preset reference in use-query.ts (we deferred applying the preset in the lib build, so the hypothetical doesn't help a reader). Collapse the duplicated WHY block in the stability test to a 3-line pointer to use-query.ts. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent e395061 commit c35eee2

3 files changed

Lines changed: 178 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'fetchium': patch
3+
---
4+
5+
Fix `useQuery` to stabilize thunk identity across re-renders. Without it, signalium allocated a new signal per render, which under some React commit orderings (React 18 / React Native) caused a spurious `getConfig.subscribe` cleanup while the consumer was still mounted.
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import { describe, it, expect, beforeEach } from 'vitest';
2+
import { render } from 'vitest-browser-react';
3+
import { ContextProvider } from 'signalium/react';
4+
import React, { useState } from 'react';
5+
import { MemoryPersistentStore, SyncQueryStore } from '../../stores/sync.js';
6+
import { QueryClient, QueryClientContext } from '../../QueryClient.js';
7+
import { t } from '../../typeDefs.js';
8+
import { Entity } from '../../proxy.js';
9+
import { sleep } from '../../__tests__/utils.js';
10+
import { useQuery, __debug_thunkAllocations, __debug_resetThunkAllocations } from '../use-query.js';
11+
import { TopicQuery } from '../../topic/TopicQuery.js';
12+
import { TopicQueryAdapter } from '../../topic/TopicQueryAdapter.js';
13+
14+
class MockStream {
15+
private _subs = new Map<string, (data: unknown) => void>();
16+
push(topic: string, data: unknown): void {
17+
this._subs.get(topic)?.(data);
18+
}
19+
subscribe(topic: string, onData: (data: unknown) => void): () => void {
20+
this._subs.set(topic, onData);
21+
return () => this._subs.delete(topic);
22+
}
23+
}
24+
25+
class MockTopicAdapter extends TopicQueryAdapter {
26+
private _stream: MockStream;
27+
private _unsubs = new Map<string, () => void>();
28+
subscribeCalls = new Map<string, number>();
29+
unsubscribeCalls = new Map<string, number>();
30+
31+
constructor(stream: MockStream) {
32+
super();
33+
this._stream = stream;
34+
}
35+
36+
preload(topic: string, data: unknown): void {
37+
this.fulfillTopic(topic, data);
38+
}
39+
40+
subscribe(topic: string): void {
41+
this.subscribeCalls.set(topic, (this.subscribeCalls.get(topic) ?? 0) + 1);
42+
const unsub = this._stream.subscribe(topic, data => this.fulfillTopic(topic, data));
43+
this._unsubs.set(topic, unsub);
44+
}
45+
46+
unsubscribe(topic: string): void {
47+
this.unsubscribeCalls.set(topic, (this.unsubscribeCalls.get(topic) ?? 0) + 1);
48+
this._unsubs.get(topic)?.();
49+
this._unsubs.delete(topic);
50+
this.clearTopic(topic);
51+
}
52+
}
53+
54+
class TopicPrice extends Entity {
55+
__typename = t.typename('TopicPrice');
56+
id = t.id;
57+
value = t.number;
58+
}
59+
60+
describe('useQuery thunk identity', () => {
61+
let client: QueryClient;
62+
let stream: MockStream;
63+
64+
beforeEach(() => {
65+
client?.destroy();
66+
stream = new MockStream();
67+
client = new QueryClient({
68+
store: new SyncQueryStore(new MemoryPersistentStore()),
69+
adapters: [new MockTopicAdapter(stream)],
70+
} as any);
71+
});
72+
73+
// Without the stable-thunk fix in `useQuery`, the counter grows with each
74+
// render. See `use-query.ts` for why a fresh thunk per render triggers a
75+
// spurious deactivate cascade.
76+
it('allocates a stable thunk across re-renders with deeply-equal args', async () => {
77+
class GetPrices extends TopicQuery {
78+
static override adapter = MockTopicAdapter;
79+
params = { walletId: t.string };
80+
topic = `balances:${this.params.walletId}`;
81+
result = { items: t.array(t.entity(TopicPrice)) };
82+
}
83+
84+
__debug_resetThunkAllocations();
85+
let bump!: () => void;
86+
87+
function Component(): React.ReactNode {
88+
// Fresh inline literal each render, deeply-equal across renders.
89+
const q = useQuery(GetPrices, { walletId: 'w1' });
90+
const [, setN] = useState(0);
91+
bump = () => setN(v => v + 1);
92+
return <div data-testid="probe">{q.isReady ? 'r' : 'l'}</div>;
93+
}
94+
95+
render(
96+
<ContextProvider contexts={[[QueryClientContext, client]]}>
97+
<Component />
98+
</ContextProvider>,
99+
);
100+
await sleep(20);
101+
102+
const afterMount = __debug_thunkAllocations;
103+
104+
for (let i = 0; i < 20; i++) {
105+
bump();
106+
await sleep(5);
107+
}
108+
await sleep(20);
109+
110+
expect(__debug_thunkAllocations - afterMount).toBe(0);
111+
});
112+
113+
it('re-allocates the thunk when args change structurally', async () => {
114+
class GetByWallet extends TopicQuery {
115+
static override adapter = MockTopicAdapter;
116+
params = { walletId: t.string };
117+
topic = `balances:${this.params.walletId}`;
118+
result = { items: t.array(t.entity(TopicPrice)) };
119+
}
120+
121+
__debug_resetThunkAllocations();
122+
let setWalletId!: (id: string) => void;
123+
124+
function Component(): React.ReactNode {
125+
const [walletId, setId] = useState('w1');
126+
setWalletId = setId;
127+
const q = useQuery(GetByWallet, { walletId });
128+
return <div data-testid="probe">{q.isReady ? 'r' : 'l'}</div>;
129+
}
130+
131+
render(
132+
<ContextProvider contexts={[[QueryClientContext, client]]}>
133+
<Component />
134+
</ContextProvider>,
135+
);
136+
await sleep(20);
137+
138+
const afterMount = __debug_thunkAllocations;
139+
140+
setWalletId('w2');
141+
await sleep(20);
142+
setWalletId('w3');
143+
await sleep(20);
144+
145+
expect(__debug_thunkAllocations - afterMount).toBe(2);
146+
});
147+
});

‎packages/fetchium/src/react/use-query.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
1+
import { useMemo } from 'react';
12
import { useReactive } from 'signalium/react';
3+
import { hashValue } from 'signalium/utils';
24
import { ExtractType, QueryPromise } from '../types.js';
35
import { fetchQuery, Query } from '../query.js';
46
import { HasRequiredKeys, Optionalize, Signalize } from '../type-utils.js';
57

8+
/**
9+
* Dev-only counter exported for tests to assert thunk identity stability
10+
* across re-renders. Stripped from production builds via `IS_DEV`.
11+
*/
12+
export let __debug_thunkAllocations = 0;
13+
export function __debug_resetThunkAllocations(): void {
14+
__debug_thunkAllocations = 0;
15+
}
16+
617
/**
718
* React hook for fetching a query.
819
*
@@ -17,5 +28,19 @@ export function useQuery<T extends Query>(
1728
? [params: Optionalize<Signalize<ExtractType<T['params']>>>]
1829
: [params?: Optionalize<Signalize<ExtractType<T['params']>>> | undefined]
1930
): QueryPromise<T> {
20-
return useReactive(() => fetchQuery(QueryClass, ...args)) as QueryPromise<T>;
31+
// Stabilize thunk identity across renders so signalium's `useReactive`
32+
// (keyed on fn identity via WeakMap) reuses the same signal. Without it,
33+
// React 18 / React Native commit ordering can flush a deactivate cascade
34+
// between unsubscribe-old and subscribe-new and tear down the relay while
35+
// a consumer is still mounted.
36+
const paramsHash = hashValue(args);
37+
const thunk = useMemo(
38+
() => {
39+
if (IS_DEV) __debug_thunkAllocations++;
40+
return () => fetchQuery(QueryClass, ...args);
41+
},
42+
// eslint-disable-next-line react-hooks/exhaustive-deps
43+
[QueryClass, paramsHash],
44+
);
45+
return useReactive(thunk) as QueryPromise<T>;
2146
}

0 commit comments

Comments
 (0)