Skip to content

Commit d832ac0

Browse files
feat: Enhance useOnyx hook to track initial mount state and improve key change handling
1 parent 27c9456 commit d832ac0

1 file changed

Lines changed: 16 additions & 5 deletions

File tree

lib/useOnyx.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
112112
// explicit reset logic — eliminating the race condition where cleanup could clobber a boolean flag.
113113
const connectedKeyRef = useRef<OnyxKey | null>(null);
114114

115+
// Tracks whether the hook has completed its initial mount subscription.
116+
// Unlike connectedKeyRef (which gets nulled by cleanup), this persists across re-subscriptions.
117+
const hasMountedRef = useRef(false);
118+
115119
// Indicates if the hook is connecting to an Onyx key.
116120
const isConnectingRef = useRef(false);
117121

@@ -264,12 +268,19 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(
264268
(onStoreChange: () => void) => {
265269
// Reset internal state so the hook properly transitions through loading
266270
// for the new key instead of preserving stale state from the previous one.
267-
previousValueRef.current = null;
268-
newValueRef.current = null;
271+
// Only reset when the key has actually changed (not on initial mount).
272+
if (hasMountedRef.current) {
273+
previousValueRef.current = null;
274+
newValueRef.current = null;
275+
sourceValueRef.current = undefined;
276+
resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}];
277+
}
278+
// Force a cache re-read on every (re)subscription so any side effects from
279+
// subscribeToKey (e.g. addNullishStorageKey for skippable collection member ids)
280+
// are reflected in the next getSnapshot. Resetting this flag does not change
281+
// resultRef by itself, so it doesn't cause an extra mount render.
269282
shouldGetCachedValueRef.current = true;
270-
sourceValueRef.current = undefined;
271-
resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}];
272-
283+
hasMountedRef.current = true;
273284
isConnectingRef.current = true;
274285
onStoreChangeFnRef.current = onStoreChange;
275286

0 commit comments

Comments
 (0)