Skip to content

Commit 07d7dfd

Browse files
committed
Move useOnyxState subscription on store change, build previousState from committed run
1 parent 77cb8e5 commit 07d7dfd

2 files changed

Lines changed: 99 additions & 23 deletions

File tree

‎lib/useOnyxState.ts‎

Lines changed: 41 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,10 @@ type SnapshotCache<T> = {
8888
};
8989

9090
type StateSubscription = {
91-
onStoreChange: () => void;
9291
keys: readonly OnyxKey[];
9392
unsubscribe: () => void;
93+
/** Moves the subscription to the keys the latest selector run read. */
94+
syncKeys: () => void;
9495
};
9596

9697
/** Runs the selector with `liveStateView` recording, and returns the set of keys it read. */
@@ -165,9 +166,33 @@ function useOnyxState<T>(selector: UseOnyxStateSelector<T>, options: UseOnyxStat
165166
// Only `subscribe` has to be referentially stable, since it controls re-subscription.
166167
// `getSnapshot` may change identity freely, so it closes over the latest selector directly.
167168
const subscribe = useCallback((onStoreChange: () => void) => {
169+
// React's store-change handler calls `getSnapshot` synchronously, so once it returns the latest
170+
// run's keys are in `lastSnapshotRef`. Moving the subscription here rather than only after a
171+
// commit matters when a run reads a new key but returns an equal output: nothing commits then.
172+
const handleStoreChange = () => {
173+
onStoreChange();
174+
subscription.syncKeys();
175+
};
176+
168177
// React subscribes after the commit, so the snapshot behind the committed value is already there.
169178
const keys = lastSnapshotRef.current?.deps ?? [];
170-
const subscription: StateSubscription = {onStoreChange, keys, unsubscribe: onyxSubscriptionManager.subscribeState(onStoreChange, keys)};
179+
const subscription: StateSubscription = {
180+
keys,
181+
unsubscribe: onyxSubscriptionManager.subscribeState(handleStoreChange, keys),
182+
syncKeys: () => {
183+
const lastSnapshot = lastSnapshotRef.current;
184+
if (lastSnapshot === null || subscription.keys === lastSnapshot.deps) {
185+
return;
186+
}
187+
subscription.unsubscribe();
188+
subscription.keys = lastSnapshot.deps;
189+
subscription.unsubscribe = onyxSubscriptionManager.subscribeState(handleStoreChange, lastSnapshot.deps);
190+
// A write that landed on a newly read key before this point fired nobody.
191+
if (!areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues)) {
192+
handleStoreChange();
193+
}
194+
},
195+
};
171196
subscriptionRef.current = subscription;
172197

173198
// `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it
@@ -180,7 +205,7 @@ function useOnyxState<T>(selector: UseOnyxStateSelector<T>, options: UseOnyxStat
180205
if (!isActive) {
181206
return;
182207
}
183-
onStoreChange();
208+
handleStoreChange();
184209
});
185210
}
186211

@@ -230,39 +255,32 @@ function useOnyxState<T>(selector: UseOnyxStateSelector<T>, options: UseOnyxStat
230255
}, [selector, selectorEquality]);
231256

232257
const value = useSyncExternalStore(subscribe, getSnapshot);
258+
// The run behind `value`. A store change between the commit and the effects below can overwrite the ref.
259+
const renderedSnapshot = lastSnapshotRef.current;
233260

234-
// Move the subscription to the keys the latest run read. It runs after the commit, so a
235-
// write that landed in between on a newly read key fired nobody; comparing the values the run saw with
236-
// the current ones catches it, the same check React does when it first subscribes.
261+
// A render can run the selector without a store change, say with a new selector, so the keys can move here too.
237262
useEffect(() => {
238-
const subscription = subscriptionRef.current;
239-
const lastSnapshot = lastSnapshotRef.current;
240-
if (subscription === null || lastSnapshot === null || subscription.keys === lastSnapshot.deps) {
241-
return;
242-
}
243-
subscription.unsubscribe();
244-
subscription.keys = lastSnapshot.deps;
245-
subscription.unsubscribe = onyxSubscriptionManager.subscribeState(subscription.onStoreChange, lastSnapshot.deps);
246-
if (!areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues)) {
247-
subscription.onStoreChange();
248-
}
263+
subscriptionRef.current?.syncKeys();
249264
});
250265

251266
// Snapshot the deps after a commit that changed the output, to serve as `previousState` on the next
252267
// selector run. Doing it here rather than in `getSnapshot` keeps that function pure and gives
253268
// `previousState` its meaning, the deps behind the last committed output: a change whose output
254269
// the equality check swallowed never commits, so it never advances past a value nobody saw. Running
255-
// only on output changes also keeps a re-render from a parent from allocating a new view.
270+
// only on output changes also keeps a re-render from a parent from allocating a new view. The values
271+
// come from the committed run, not the store, so a write landing before this effect still reads as a change.
256272
useEffect(() => {
257-
const currentDepValues: Record<OnyxKey, OnyxValue<OnyxKey>> = {};
258-
for (const dep of lastSnapshotRef.current?.deps ?? []) {
259-
currentDepValues[dep] = onyxSubscriptionManager.getState(dep);
273+
const committedDepValues: Record<OnyxKey, OnyxValue<OnyxKey>> = {};
274+
if (renderedSnapshot !== null) {
275+
for (const [index, dep] of renderedSnapshot.deps.entries()) {
276+
committedDepValues[dep] = renderedSnapshot.depValues[index];
277+
}
260278
}
261279
previousViewRef.current = createStateView((key) => {
262280
previousStateReadRef.current = true;
263-
return currentDepValues[key];
281+
return committedDepValues[key];
264282
});
265-
}, [value]);
283+
}, [value]); // eslint-disable-line react-hooks/exhaustive-deps
266284

267285
return value;
268286
}

‎tests/unit/useOnyxStateTest.tsx‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {act, renderHook} from '@testing-library/react-native';
2+
import {useLayoutEffect} from 'react';
23

34
import type {OnyxStateView} from '../../lib/useOnyxState';
45
import type GenericCollection from '../utils/GenericCollection';
@@ -401,5 +402,62 @@ describe('useOnyxState', () => {
401402
await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'a'));
402403
expect(result.current).toEqual({first: 'a', second: 'b'});
403404
});
405+
406+
it('should start listening to a newly read key when the output stays the same', async () => {
407+
// Given a branch that reads OTHER_TEST only once TEST_KEY is 'on', and returns null either way
408+
await Onyx.set(ONYXKEYS.TEST_KEY, 'off');
409+
const {result} = renderHook(() => useOnyxState((state) => (state[ONYXKEYS.TEST_KEY] === 'on' ? (state[ONYXKEYS.OTHER_TEST] ?? null) : null)));
410+
await act(async () => waitForPromisesToResolve());
411+
412+
// When the branch flips without changing the output, so nothing re-renders
413+
await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'on'));
414+
expect(result.current).toBeNull();
415+
416+
// Then a write to the newly read key still reaches the hook
417+
await act(async () => Onyx.set(ONYXKEYS.OTHER_TEST, 'value'));
418+
expect(result.current).toEqual('value');
419+
});
420+
421+
it('should follow a pointer that arrives before the record it points at', async () => {
422+
// Given a selector that looks up a member through a pointer key, with neither stored yet
423+
const {result} = renderHook(() =>
424+
useOnyxState((state) => (state[ONYXKEYS.TEST_KEY] ? ((state[`${COLLECTION}${state[ONYXKEYS.TEST_KEY] as string}`] as {name: string} | undefined)?.name ?? null) : null)),
425+
);
426+
await act(async () => waitForPromisesToResolve());
427+
428+
// When the pointer lands first, the output stays null
429+
await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, '1'));
430+
expect(result.current).toBeNull();
431+
432+
// Then the record it points at still updates the hook when it arrives
433+
await act(async () => Onyx.merge(MEMBER_1, {name: 'one'}));
434+
expect(result.current).toEqual('one');
435+
});
436+
});
437+
438+
describe('previousState after a write between commit and effects', () => {
439+
it('should keep the values the committed run saw, not a later write', async () => {
440+
// Given a selector that reports the previous and current value of TEST_KEY
441+
await Onyx.set(ONYXKEYS.TEST_KEY, 'a');
442+
const {result} = renderHook(() => {
443+
const value = useOnyxState((state, previousState) => `${previousState?.[ONYXKEYS.TEST_KEY] as string}->${state[ONYXKEYS.TEST_KEY] as string}`);
444+
// Layout effects run after the commit but before passive effects, which is where the hook builds previousState
445+
useLayoutEffect(() => {
446+
if (value !== 'a->b') {
447+
return;
448+
}
449+
Onyx.set(ONYXKEYS.TEST_KEY, 'c');
450+
}, [value]);
451+
return value;
452+
});
453+
await act(async () => waitForPromisesToResolve());
454+
455+
// When 'b' commits and 'c' is written before the passive effects run
456+
await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'b'));
457+
await act(async () => waitForPromisesToResolve());
458+
459+
// Then previousState holds 'b', the value behind the committed output, so the b->c change is not lost
460+
expect(result.current).toEqual('b->c');
461+
});
404462
});
405463
});

0 commit comments

Comments
 (0)