From b8b5fc788b6182148bbf83a74abae5911e66a4e3 Mon Sep 17 00:00:00 2001 From: VickyStash Date: Tue, 21 Apr 2026 09:31:29 +0200 Subject: [PATCH 1/2] Fix useOnyx to skip state reset on initial mount --- lib/useOnyx.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/useOnyx.ts b/lib/useOnyx.ts index be7521048..ba099562a 100644 --- a/lib/useOnyx.ts +++ b/lib/useOnyx.ts @@ -112,6 +112,10 @@ function useOnyx>( // explicit reset logic — eliminating the race condition where cleanup could clobber a boolean flag. const connectedKeyRef = useRef(null); + // Tracks whether the hook has completed its initial mount subscription. + // Unlike connectedKeyRef (which gets nulled by cleanup), this persists across re-subscriptions. + const hasMountedRef = useRef(false); + // Indicates if the hook is connecting to an Onyx key. const isConnectingRef = useRef(false); @@ -264,12 +268,15 @@ function useOnyx>( (onStoreChange: () => void) => { // Reset internal state so the hook properly transitions through loading // for the new key instead of preserving stale state from the previous one. - previousValueRef.current = null; - newValueRef.current = null; - shouldGetCachedValueRef.current = true; - sourceValueRef.current = undefined; - resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}]; - + // Only reset when the key has actually changed (not on initial mount). + if (hasMountedRef.current) { + previousValueRef.current = null; + newValueRef.current = null; + shouldGetCachedValueRef.current = true; + sourceValueRef.current = undefined; + resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}]; + } + hasMountedRef.current = true; isConnectingRef.current = true; onStoreChangeFnRef.current = onStoreChange; From a719f47fa9a12de13afce5bd57d5d361287af2bd Mon Sep 17 00:00:00 2001 From: kubabutkiewicz Date: Wed, 22 Apr 2026 11:13:33 +0200 Subject: [PATCH 2/2] fix tests --- lib/useOnyx.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/useOnyx.ts b/lib/useOnyx.ts index ba099562a..0ce1a4a63 100644 --- a/lib/useOnyx.ts +++ b/lib/useOnyx.ts @@ -272,10 +272,14 @@ function useOnyx>( if (hasMountedRef.current) { previousValueRef.current = null; newValueRef.current = null; - shouldGetCachedValueRef.current = true; sourceValueRef.current = undefined; resultRef.current = [undefined, {status: options?.initWithStoredValues === false ? 'loaded' : 'loading'}]; } + // Force a cache re-read on every (re)subscription so any side effects from + // subscribeToKey (e.g. addNullishStorageKey for skippable collection member ids) + // are reflected in the next getSnapshot. Resetting this flag does not change + // resultRef by itself, so it doesn't cause an extra mount render. + shouldGetCachedValueRef.current = true; hasMountedRef.current = true; isConnectingRef.current = true; onStoreChangeFnRef.current = onStoreChange;