Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ function useOnyx<TKey extends OnyxKey, TReturnValue = OnyxValue<TKey>>(key: TKey
if (!shouldGetCachedValueRef.current) {
const cachedResult = onyxSnapshotCache.getCachedResult<UseOnyxResult<TReturnValue>>(key, cacheKey);
if (cachedResult !== undefined) {
// The slot is shared by all subscribers of the same (key, selector) pair, so it can hold a content-equal
// result computed by another subscriber. Keep our own result then, otherwise we would needlessly change
// this hook's result identity and re-render its consumer.
if (cachedResult !== resultRef.current && memoizedShallowEqual(cachedResult[0], resultRef.current[0]) && cachedResult[1].status === resultRef.current[1].status) {
return resultRef.current;
}
resultRef.current = cachedResult;
return cachedResult;
}
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/useOnyxTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,28 @@ describe('useOnyx', () => {
expect(oldResult).toBe(result.current);
});

it('should keep result identity when a new subscriber with the same key and selector mounts', async () => {
Onyx.set(ONYXKEYS.TEST_KEY, {id: 'test_id', name: 'test_name'});

const selector = ((entry: OnyxEntry<{id: string; name: string}>) => ({id: entry?.id})) as UseOnyxSelector<OnyxKey, {id?: string}>;

const {result, rerender} = renderHook(() => useOnyx(ONYXKEYS.TEST_KEY, {selector}));

await act(async () => waitForPromisesToResolve());

const oldResult = result.current;

// A subscriber that mounts later computes its own content-equal selector output and publishes it into the shared snapshot cache slot.
renderHook(() => useOnyx(ONYXKEYS.TEST_KEY, {selector}));

await act(async () => waitForPromisesToResolve());

rerender(undefined);

// must be the same reference — the new subscriber's content-equal result must not replace it
expect(result.current).toBe(oldResult);
});

it('should always use the current selector reference to return new data', async () => {
Onyx.set(ONYXKEYS.TEST_KEY, {id: 'test_id', name: 'test_name'});

Expand Down
Loading