Skip to content

Commit b8b5fc7

Browse files
committed
Fix useOnyx to skip state reset on initial mount
1 parent 27c9456 commit b8b5fc7

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

lib/useOnyx.ts

Lines changed: 13 additions & 6 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,15 @@ 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;
269-
shouldGetCachedValueRef.current = true;
270-
sourceValueRef.current = undefined;
271-
resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}];
272-
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+
shouldGetCachedValueRef.current = true;
276+
sourceValueRef.current = undefined;
277+
resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}];
278+
}
279+
hasMountedRef.current = true;
273280
isConnectingRef.current = true;
274281
onStoreChangeFnRef.current = onStoreChange;
275282

0 commit comments

Comments
 (0)