From 6fde1726614c7fb5aeb01cdbd1fcf22a83c6e378 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Tue, 17 Nov 2026 17:22:35 +0100 Subject: [PATCH 1/4] Auto-track useOnyxState dependencies --- lib/useOnyxState.ts | 108 ++++++++++--- .../useOnyxStateAutoDeps.perf-test.tsx | 151 ++++++++++++++++++ tests/types/useOnyxState.ts | 5 + tests/unit/useOnyxStateTest.tsx | 99 ++++++++++++ 4 files changed, 345 insertions(+), 18 deletions(-) create mode 100644 tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx diff --git a/lib/useOnyxState.ts b/lib/useOnyxState.ts index 604198775..112fa8f16 100644 --- a/lib/useOnyxState.ts +++ b/lib/useOnyxState.ts @@ -62,8 +62,13 @@ type UseOnyxStateOptions OnyxValue) return new Proxy>({}, handler) as unknown as OnyxStateView; } -const liveStateView = createStateView((key) => onyxSubscriptionManager.getState(key as OnyxKey)); +/** Collects the keys the running auto-tracked selector reads from `liveStateView`, `null` when nothing is recording. */ +let activeRecorder: Set | null = null; + +const liveStateView = createStateView((key) => { + activeRecorder?.add(key as OnyxKey); + return onyxSubscriptionManager.getState(key as OnyxKey); +}); type SnapshotCache = { value: T; @@ -106,9 +117,33 @@ type SnapshotCache = { previousView: OnyxStateView | undefined; /** Whether the run that produced `value` read `previousState`. A run that ignored it can't care that it moved. */ readPreviousState: boolean; + /** The declared deps, or the keys the run read when auto-tracking. Same reference while the set is unchanged. */ + deps: readonly OnyxKey[]; depValues: Array>; }; +type StateSubscription = { + onStoreChange: () => void; + keys: readonly OnyxKey[]; + unsubscribe: () => void; +}; + +/** Runs the selector with `liveStateView` recording, and returns the set of keys it read. */ +function recordReads(run: () => T): {output: T; keys: Set} { + const keys = new Set(); + const outerRecorder = activeRecorder; + activeRecorder = keys; + try { + return {output: run(), keys}; + } finally { + activeRecorder = outerRecorder; + } +} + +function isSameKeySet(keys: readonly OnyxKey[], recorded: Set): boolean { + return keys.length === recorded.size && keys.every((key) => recorded.has(key)); +} + /** True when every dep still reads as the same reference it had when `depValues` was taken. */ function areDepValuesUnchanged(deps: readonly OnyxKey[], depValues: Array>): boolean { if (deps.length !== depValues.length) { @@ -142,28 +177,38 @@ function defaultSelectorEquality(a: T, b: T): boolean { * `previousState` to walk only what changed (structural sharing keeps unchanged collection members * reference-equal, so each step is O(1)) or as a real input, say to emit a delta. * - * Re-runs when any declared dep changes, and skips the React update when the output is equal to the + * Re-runs when any declared or tracked dep changes, and skips the React update when the output is equal to the * previous one, per `selectorEquality`. * * Mounting before `Onyx.init` has hydrated runs the selector against an empty state and re-runs it * once init lands. There is no status channel, so a consumer that must tell "not hydrated yet" from * "absent" has to carry that in its own output. */ -function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStateOptions): T { +function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStateOptions = {}): T { const {dependencies, selectorEquality = defaultSelectorEquality} = options; // Consumers pass an inline array literal, so key the memo on the contents: `depsArray` only gets // a new reference when the set of keys changes, which keeps `subscribe` from re-subscribing on // every render. The space separator is safe, Onyx keys never contain spaces. React Compiler // can't preserve content-keying, so this hook opts out of it and memoizes by hand. - const depsKey = dependencies.join(' '); - const depsArray = useMemo(() => [...dependencies], [depsKey]); // eslint-disable-line react-hooks/exhaustive-deps, react-hooks/preserve-manual-memoization + // `undefined` means the deps are auto-tracked. + const depsKey = dependencies?.join(' '); + const depsArray = useMemo(() => (dependencies ? [...dependencies] : undefined), [depsKey]); // eslint-disable-line react-hooks/exhaustive-deps, react-hooks/preserve-manual-memoization + + // Mutated only in the post-commit effect below, so it stays frozen across a render's + // `getSnapshot` calls and every one of them computes the same output. + const previousViewRef = useRef(undefined); + const lastSnapshotRef = useRef | null>(null); + const subscriptionRef = useRef(null); // Only `subscribe` has to be referentially stable, since it controls re-subscription. // `getSnapshot` may change identity freely, so it closes over the latest selector directly. const subscribe = useCallback( (onStoreChange: () => void) => { - const unsubscribe = onyxSubscriptionManager.subscribeState(onStoreChange, depsArray); + // React subscribes after the commit, so the snapshot behind the committed value is already there. + const keys = depsArray ?? lastSnapshotRef.current?.deps ?? []; + const subscription: StateSubscription = {onStoreChange, keys, unsubscribe: onyxSubscriptionManager.subscribeState(onStoreChange, keys)}; + subscriptionRef.current = subscription; // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it // finished saw an empty state and would never hear the stored values arrive. Re-read once @@ -181,17 +226,15 @@ function useOnyxState(selecto return () => { isActive = false; - unsubscribe(); + subscription.unsubscribe(); + if (subscriptionRef.current === subscription) { + subscriptionRef.current = null; + } }; }, [depsArray], ); - // Mutated only in the post-commit effect below, so it stays frozen across a render's - // `getSnapshot` calls and every one of them computes the same output. - const previousViewRef = useRef(undefined); - const lastSnapshotRef = useRef | null>(null); - // Flipped by the `previousState` view when the selector reads a key off it. Read straight after the // selector returns, so it describes that run only. const previousStateReadRef = useRef(false); @@ -209,27 +252,56 @@ function useOnyxState(selecto lastSnapshot !== null && lastSnapshot.selector === selector && (!lastSnapshot.readPreviousState || lastSnapshot.previousView === previousView) && - areDepValuesUnchanged(depsArray, lastSnapshot.depValues) + (depsArray === undefined || lastSnapshot.deps === depsArray) && + areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues) ) { return lastSnapshot.value; } - const depValues = depsArray.map((dep) => onyxSubscriptionManager.getState(dep)); previousStateReadRef.current = false; // The views carry every key at runtime; the narrowing is a constraint on what a selector may // read, so hand them over as the declared shape. - const output = selector(liveStateView as OnyxStateViewFor, previousView as OnyxStateViewFor | undefined); + const runSelector = () => selector(liveStateView as OnyxStateViewFor, previousView as OnyxStateViewFor | undefined); + let output: T; + let deps: readonly OnyxKey[]; + if (depsArray) { + output = runSelector(); + deps = depsArray; + } else { + const run = recordReads(runSelector); + output = run.output; + // Keep the previous array while the set is unchanged, so the effect below can tell by reference. + deps = lastSnapshot !== null && isSameKeySet(lastSnapshot.deps, run.keys) ? lastSnapshot.deps : [...run.keys]; + } const readPreviousState = previousStateReadRef.current; + const depValues = deps.map((dep) => onyxSubscriptionManager.getState(dep)); // Hand back the previous reference when the output is equal, so React bails out via `===` // and an unchanged store keeps returning the same value even as `getSnapshot`'s identity moves. const value = lastSnapshot !== null && selectorEquality(lastSnapshot.value, output) ? lastSnapshot.value : output; - lastSnapshotRef.current = {value, selector, previousView, readPreviousState, depValues}; + lastSnapshotRef.current = {value, selector, previousView, readPreviousState, deps, depValues}; return value; }, [selector, selectorEquality, depsArray]); const value = useSyncExternalStore(subscribe, getSnapshot); + // Auto-tracking: move the subscription to the keys the latest run read. It runs after the commit, so a + // write that landed in between on a newly read key fired nobody; comparing the values the run saw with + // the current ones catches it, the same check React does when it first subscribes. + useEffect(() => { + const subscription = subscriptionRef.current; + const lastSnapshot = lastSnapshotRef.current; + if (depsArray !== undefined || subscription === null || lastSnapshot === null || subscription.keys === lastSnapshot.deps) { + return; + } + subscription.unsubscribe(); + subscription.keys = lastSnapshot.deps; + subscription.unsubscribe = onyxSubscriptionManager.subscribeState(subscription.onStoreChange, lastSnapshot.deps); + if (!areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues)) { + subscription.onStoreChange(); + } + }); + // Snapshot the deps after a commit that changed the output, to serve as `previousState` on the next // selector run. Doing it here rather than in `getSnapshot` keeps that function pure and gives // `previousState` its meaning, the deps behind the last committed output: a change whose output @@ -237,7 +309,7 @@ function useOnyxState(selecto // only on output changes also keeps a re-render from a parent from allocating a new view. useEffect(() => { const currentDepValues: Record> = {}; - for (const dep of depsArray) { + for (const dep of depsArray ?? lastSnapshotRef.current?.deps ?? []) { currentDepValues[dep] = onyxSubscriptionManager.getState(dep); } previousViewRef.current = createStateView((key) => { diff --git a/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx b/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx new file mode 100644 index 000000000..211b204df --- /dev/null +++ b/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx @@ -0,0 +1,151 @@ +import {act, screen} from '@testing-library/react-native'; +import fs from 'fs'; + +import React from 'react'; +import {Text, View} from 'react-native'; +import {measureRenders} from 'reassure'; + +import type {OnyxKey} from '../../lib'; +import type {OnyxStateView} from '../../lib/useOnyxState'; + +import Onyx from '../../lib'; +import useOnyxState from '../../lib/useOnyxState'; + +/** `collection` declares `report_`, `member` hand-declares `report_`, `auto` omits `dependencies`. */ +const MODE = (process.env.UOS_DEPS ?? 'auto') as 'collection' | 'member' | 'auto'; +const COLLECTION_KEY = 'report_'; +const UPDATES = 5; + +type Report = {reportID: string; name: string; total: number}; + +const memberKey = (index: number) => `${COLLECTION_KEY}${index}`; + +const seedCollection = async (size: number) => { + const collection = Object.fromEntries(Array.from({length: size}, (_, index) => [memberKey(index), {reportID: String(index), name: `report ${index}`, total: index}])); + await Onyx.mergeCollection(COLLECTION_KEY, collection); +}; + +let selectorRuns = 0; + +function depsFor(key: OnyxKey) { + if (MODE === 'collection') { + return {dependencies: [COLLECTION_KEY] as OnyxKey[]}; + } + if (MODE === 'member') { + return {dependencies: [key]}; + } + return undefined; +} + +function Row({index}: {index: number}) { + const key = memberKey(index); + const name = useOnyxState((state: OnyxStateView) => { + selectorRuns++; + return (state[key] as Report | undefined)?.name; + }, depsFor(key)); + return {`row ${index}: ${name ?? ''}`}; +} + +function Rows({count}: {count: number}) { + return ( + + {Array.from({length: count}, (_, index) => ( + + ))} + + ); +} + +function CollectionCount() { + const count = useOnyxState( + (state: OnyxStateView) => { + selectorRuns++; + return Object.keys((state[COLLECTION_KEY] as Record | undefined) ?? {}).length; + }, + MODE === 'auto' ? undefined : {dependencies: [COLLECTION_KEY] as OnyxKey[]}, + ); + return {`count: ${count}`}; +} + +const stats: Record = {}; + +const runUpdates = async (update: (step: number) => Promise) => { + selectorRuns = 0; + const start = performance.now(); + for (let step = 0; step < UPDATES; step++) { + await act(async () => { + await update(step); + }); + } + const name = expect.getState().currentTestName ?? 'unknown'; + stats[name] ??= {ms: [], selectorRuns: []}; + stats[name].ms.push(performance.now() - start); + stats[name].selectorRuns.push(selectorRuns); +}; + +describe('useOnyxState auto-tracked deps (issue 3020)', () => { + beforeAll(() => { + Onyx.init({keys: {COLLECTION: {REPORT: COLLECTION_KEY}}}); + }); + + afterEach(async () => { + await Onyx.clear(); + }); + + afterAll(() => { + const output = process.env.UPDATE_TIMINGS_FILE; + if (output) { + fs.writeFileSync(output, JSON.stringify({mode: MODE, stats})); + } + }); + + describe.each([100, 1000])('%i rows', (rows) => { + test('one rendered row member changes', async () => { + await measureRenders(, { + beforeEach: () => seedCollection(rows * 2), + scenario: async () => { + await screen.findByText('row 0: report 0'); + await runUpdates((step) => Onyx.merge(memberKey(0), {name: `renamed ${step}`})); + await screen.findByText(`row 0: renamed ${UPDATES - 1}`); + }, + afterEach: () => Onyx.clear(), + }); + }); + + test('member outside the rows changes', async () => { + await measureRenders(, { + beforeEach: () => seedCollection(rows * 2), + scenario: async () => { + await screen.findByText('row 0: report 0'); + await runUpdates((step) => Onyx.merge(memberKey(rows + step), {name: `renamed ${step}`})); + }, + afterEach: () => Onyx.clear(), + }); + }); + + test('mergeCollection over 50 members outside the rows', async () => { + await measureRenders(, { + beforeEach: () => seedCollection(rows * 2), + scenario: async () => { + await screen.findByText('row 0: report 0'); + await runUpdates((step) => Onyx.mergeCollection(COLLECTION_KEY, Object.fromEntries(Array.from({length: 50}, (_, i) => [memberKey(rows + i), {total: step * 1000 + i}])))); + }, + afterEach: () => Onyx.clear(), + }); + }); + }); + + test('selector reading the collection root, member changes', async () => { + await measureRenders(, { + beforeEach: () => seedCollection(1000), + scenario: async () => { + await screen.findByText('count: 1000'); + await runUpdates((step) => Onyx.merge(memberKey(step), {total: step + 1})); + }, + afterEach: () => Onyx.clear(), + }); + }); +}); diff --git a/tests/types/useOnyxState.ts b/tests/types/useOnyxState.ts index b6a32eafe..a435e94a8 100644 --- a/tests/types/useOnyxState.ts +++ b/tests/types/useOnyxState.ts @@ -109,6 +109,10 @@ function aDeclaredRootGrantsItsMembers() { return useOnyxState((state) => state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]?.str, {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}); } +function autoTrackedReadsAnyKey() { + return useOnyxState((state) => `${state[ONYX_KEYS.TEST_KEY] ?? ''}${state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]?.str ?? ''}`); +} + export { readCollectionRoot, readCollectionMember, @@ -120,4 +124,5 @@ export { cannotReadAnUndeclaredCollection, cannotReadAnUndeclaredKeyFromPreviousState, aDeclaredRootGrantsItsMembers, + autoTrackedReadsAnyKey, }; diff --git a/tests/unit/useOnyxStateTest.tsx b/tests/unit/useOnyxStateTest.tsx index 38f54bfaf..3beaa0333 100644 --- a/tests/unit/useOnyxStateTest.tsx +++ b/tests/unit/useOnyxStateTest.tsx @@ -364,4 +364,103 @@ describe('useOnyxState', () => { expect(result.current).toEqual({previous: undefined, current: 'from storage'}); }); }); + + describe('auto-tracked dependencies', () => { + it('should return the value and update when a read key changes', async () => { + await Onyx.set(ONYXKEYS.TEST_KEY, 'hello'); + const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY])); + await act(async () => waitForPromisesToResolve()); + + expect(result.current).toEqual('hello'); + + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'updated')); + + expect(result.current).toEqual('updated'); + }); + + it('should not run the selector when a sibling of the read member changes', async () => { + await Onyx.mergeCollection(COLLECTION, {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}} as GenericCollection); + const selector = jest.fn((state: OnyxStateView) => (state[MEMBER_1] as {id: number} | undefined)?.id); + const {result} = renderHook(() => useOnyxState(selector)); + await act(async () => waitForPromisesToResolve()); + const callCountAfterMount = selector.mock.calls.length; + + await act(async () => Onyx.merge(MEMBER_2, {id: 22})); + await act(async () => Onyx.mergeCollection(COLLECTION, {[MEMBER_2]: {id: 222}} as GenericCollection)); + + expect(selector).toHaveBeenCalledTimes(callCountAfterMount); + expect(result.current).toEqual(1); + + await act(async () => Onyx.merge(MEMBER_1, {id: 11})); + + expect(result.current).toEqual(11); + }); + + it('should follow a lookup to the key it points at', async () => { + await Onyx.mergeCollection(COLLECTION, {[MEMBER_1]: {name: 'one'}, [MEMBER_2]: {name: 'two'}} as GenericCollection); + await Onyx.set(ONYXKEYS.TEST_KEY, '1'); + const selector = jest.fn((state: OnyxStateView) => (state[`${COLLECTION}${state[ONYXKEYS.TEST_KEY] as string}`] as {name: string} | undefined)?.name); + const {result} = renderHook(() => useOnyxState(selector)); + await act(async () => waitForPromisesToResolve()); + + expect(result.current).toEqual('one'); + + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, '2')); + expect(result.current).toEqual('two'); + + const callCountAfterSwitch = selector.mock.calls.length; + await act(async () => Onyx.merge(MEMBER_1, {name: 'one changed'})); + expect(selector).toHaveBeenCalledTimes(callCountAfterSwitch); + + await act(async () => Onyx.merge(MEMBER_2, {name: 'two changed'})); + expect(result.current).toEqual('two changed'); + }); + + it('should start listening to a key a branch reads for the first time', async () => { + await Onyx.set(ONYXKEYS.TEST_KEY, 'off'); + const {result} = renderHook(() => useOnyxState((state) => (state[ONYXKEYS.TEST_KEY] === 'on' ? state[ONYXKEYS.OTHER_TEST] : 'disabled'))); + await act(async () => waitForPromisesToResolve()); + + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'on')); + expect(result.current).toBeUndefined(); + + await act(async () => Onyx.set(ONYXKEYS.OTHER_TEST, 'value')); + expect(result.current).toEqual('value'); + }); + + it('should re-run on any member write when the selector reads the collection root', async () => { + const {result} = renderHook(() => useOnyxState((state) => Object.keys(state[COLLECTION] ?? {}).length)); + await act(async () => waitForPromisesToResolve()); + + await act(async () => Onyx.merge(MEMBER_1, {id: 1})); + expect(result.current).toEqual(1); + + await act(async () => Onyx.merge(MEMBER_2, {id: 2})); + expect(result.current).toEqual(2); + }); + + it('should keep tracking per hook when several hooks are mounted', async () => { + const {result} = renderHook(() => ({ + first: useOnyxState((state) => state[ONYXKEYS.TEST_KEY]), + second: useOnyxState((state) => state[ONYXKEYS.OTHER_TEST]), + })); + await act(async () => waitForPromisesToResolve()); + + await act(async () => Onyx.set(ONYXKEYS.OTHER_TEST, 'b')); + expect(result.current).toEqual({first: undefined, second: 'b'}); + + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'a')); + expect(result.current).toEqual({first: 'a', second: 'b'}); + }); + + it('should expose the tracked keys through previousState after a change', async () => { + await Onyx.set(ONYXKEYS.TEST_KEY, 'first'); + const {result} = renderHook(() => useOnyxState((state, previousState) => `${previousState?.[ONYXKEYS.TEST_KEY] as string}->${state[ONYXKEYS.TEST_KEY] as string}`)); + await act(async () => waitForPromisesToResolve()); + + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'second')); + + expect(result.current).toEqual('first->second'); + }); + }); }); From 77cb8e539054c4d96a9ce58b702ff2ec3f585a12 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Wed, 18 Nov 2026 11:30:06 +0100 Subject: [PATCH 2/4] Drop declared useOnyxState dependencies, keep auto-tracking only --- lib/useOnyxState.ts | 156 ++++++------------ .../useOnyxStateAutoDeps.perf-test.tsx | 28 +--- tests/types/useOnyxState.ts | 151 ++++++----------- tests/unit/useOnyxStateTest.tsx | 147 +++++------------ 4 files changed, 148 insertions(+), 334 deletions(-) diff --git a/lib/useOnyxState.ts b/lib/useOnyxState.ts index 112fa8f16..b495aeb3f 100644 --- a/lib/useOnyxState.ts +++ b/lib/useOnyxState.ts @@ -1,5 +1,5 @@ import {deepEqual} from 'fast-equals'; -import {useCallback, useEffect, useMemo, useRef, useSyncExternalStore} from 'react'; +import {useCallback, useEffect, useRef, useSyncExternalStore} from 'react'; import type {CollectionKeyBase, KeyValueMapping, OnyxCollection, OnyxKey, OnyxValue} from './types'; @@ -32,44 +32,9 @@ type OnyxStateView = { readonly [K in OnyxKey]: OnyxValue; } & OnyxCollectionRootsView; -/** Declaring a collection root also grants its members: any member write fires the root. */ -type DeclaredKeys = TDependency extends CollectionKeyBase ? TDependency | `${TDependency}${string}` : TDependency; - -/** - * The state view a selector gets, holding only the keys its `dependencies` declared. Reading anything - * else is the bug this prevents: the key has no listener, and the snapshot cache skips the selector - * while the declared deps keep their references, so the value would sit there stale. - * - * Collection roots are spelled out a second time for the reason `OnyxCollectionRootsView` exists, and - * the whole thing falls back to the full view when the dependency list is not a literal, since there - * is then nothing to narrow to. - */ -type OnyxStateViewFor = OnyxKey extends TDependencies[number] - ? OnyxStateView - : { - readonly [K in DeclaredKeys]: OnyxValue; - } & { - readonly [K in Extract]: OnyxCollection; - }; - -type UseOnyxStateSelector = ( - state: OnyxStateViewFor, - previousState: OnyxStateViewFor | undefined, -) => T; - -type UseOnyxStateOptions = { - /** - * Keys the selector reads. It re-runs when one of them changes; a collection key counts as a - * single dep, so any member change triggers a re-run. The selector's `state` only carries these - * keys, so reading anything else is a type error rather than a value that silently goes stale. - * - * Omit it to track the keys automatically: each selector run records the keys it read from `state`, - * and the hook subscribes to exactly those. A run's output depends only on what it read, so a key - * it skipped can't change it until a key it did read changes and the selector runs again. Reading - * `report_1` then subscribes to that member only, not the whole `report_` collection. - */ - dependencies?: TDependencies; +type UseOnyxStateSelector = (state: OnyxStateView, previousState: OnyxStateView | undefined) => T; +type UseOnyxStateOptions = { /** * Equality for the selector's output. Defaults to `===` with a deep-equal fallback for objects. * When it returns true, the React update is skipped. @@ -103,7 +68,7 @@ function createStateView(snapshotProvider: (key: OnyxKey) => OnyxValue) return new Proxy>({}, handler) as unknown as OnyxStateView; } -/** Collects the keys the running auto-tracked selector reads from `liveStateView`, `null` when nothing is recording. */ +/** Collects the keys the running selector reads from `liveStateView`, `null` when nothing is recording. */ let activeRecorder: Set | null = null; const liveStateView = createStateView((key) => { @@ -111,13 +76,13 @@ const liveStateView = createStateView((key) => { return onyxSubscriptionManager.getState(key as OnyxKey); }); -type SnapshotCache = { +type SnapshotCache = { value: T; - selector: UseOnyxStateSelector; + selector: UseOnyxStateSelector; previousView: OnyxStateView | undefined; /** Whether the run that produced `value` read `previousState`. A run that ignored it can't care that it moved. */ readPreviousState: boolean; - /** The declared deps, or the keys the run read when auto-tracking. Same reference while the set is unchanged. */ + /** The keys the run read. Same reference while the set is unchanged. */ deps: readonly OnyxKey[]; depValues: Array>; }; @@ -173,67 +138,60 @@ function defaultSelectorEquality(a: T, b: T): boolean { /** * Subscribes a component to a value derived from several Onyx keys. The selector gets a `state` view - * and a `previousState` view holding the declared deps as of the last committed render. It can use + * and a `previousState` view holding the keys it read as of the last committed render. It can use * `previousState` to walk only what changed (structural sharing keeps unchanged collection members * reference-equal, so each step is O(1)) or as a real input, say to emit a delta. * - * Re-runs when any declared or tracked dep changes, and skips the React update when the output is equal to the - * previous one, per `selectorEquality`. + * Each selector run records the keys it read from `state`, and the hook subscribes to exactly those. + * A run's output depends only on what it read, so a key it skipped can't change it until a key it did + * read changes and the selector runs again. Reading `report_1` subscribes to that member only, while + * reading the `report_` root subscribes to every member. + * + * Skips the React update when the output is equal to the previous one, per `selectorEquality`. * * Mounting before `Onyx.init` has hydrated runs the selector against an empty state and re-runs it * once init lands. There is no status channel, so a consumer that must tell "not hydrated yet" from * "absent" has to carry that in its own output. */ -function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStateOptions = {}): T { - const {dependencies, selectorEquality = defaultSelectorEquality} = options; - - // Consumers pass an inline array literal, so key the memo on the contents: `depsArray` only gets - // a new reference when the set of keys changes, which keeps `subscribe` from re-subscribing on - // every render. The space separator is safe, Onyx keys never contain spaces. React Compiler - // can't preserve content-keying, so this hook opts out of it and memoizes by hand. - // `undefined` means the deps are auto-tracked. - const depsKey = dependencies?.join(' '); - const depsArray = useMemo(() => (dependencies ? [...dependencies] : undefined), [depsKey]); // eslint-disable-line react-hooks/exhaustive-deps, react-hooks/preserve-manual-memoization +function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStateOptions = {}): T { + const {selectorEquality = defaultSelectorEquality} = options; // Mutated only in the post-commit effect below, so it stays frozen across a render's // `getSnapshot` calls and every one of them computes the same output. const previousViewRef = useRef(undefined); - const lastSnapshotRef = useRef | null>(null); + const lastSnapshotRef = useRef | null>(null); const subscriptionRef = useRef(null); // Only `subscribe` has to be referentially stable, since it controls re-subscription. // `getSnapshot` may change identity freely, so it closes over the latest selector directly. - const subscribe = useCallback( - (onStoreChange: () => void) => { - // React subscribes after the commit, so the snapshot behind the committed value is already there. - const keys = depsArray ?? lastSnapshotRef.current?.deps ?? []; - const subscription: StateSubscription = {onStoreChange, keys, unsubscribe: onyxSubscriptionManager.subscribeState(onStoreChange, keys)}; - subscriptionRef.current = subscription; + const subscribe = useCallback((onStoreChange: () => void) => { + // React subscribes after the commit, so the snapshot behind the committed value is already there. + const keys = lastSnapshotRef.current?.deps ?? []; + const subscription: StateSubscription = {onStoreChange, keys, unsubscribe: onyxSubscriptionManager.subscribeState(onStoreChange, keys)}; + subscriptionRef.current = subscription; + + // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it + // finished saw an empty state and would never hear the stored values arrive. Re-read once + // init lands. + const initTask = OnyxUtils.getDeferredInitTask(); + let isActive = true; + if (!initTask.isResolved) { + initTask.promise.then(() => { + if (!isActive) { + return; + } + onStoreChange(); + }); + } - // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it - // finished saw an empty state and would never hear the stored values arrive. Re-read once - // init lands. - const initTask = OnyxUtils.getDeferredInitTask(); - let isActive = true; - if (!initTask.isResolved) { - initTask.promise.then(() => { - if (!isActive) { - return; - } - onStoreChange(); - }); + return () => { + isActive = false; + subscription.unsubscribe(); + if (subscriptionRef.current === subscription) { + subscriptionRef.current = null; } - - return () => { - isActive = false; - subscription.unsubscribe(); - if (subscriptionRef.current === subscription) { - subscriptionRef.current = null; - } - }; - }, - [depsArray], - ); + }; + }, []); // Flipped by the `previousState` view when the selector reads a key off it. Read straight after the // selector returns, so it describes that run only. @@ -252,27 +210,15 @@ function useOnyxState(selecto lastSnapshot !== null && lastSnapshot.selector === selector && (!lastSnapshot.readPreviousState || lastSnapshot.previousView === previousView) && - (depsArray === undefined || lastSnapshot.deps === depsArray) && areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues) ) { return lastSnapshot.value; } previousStateReadRef.current = false; - // The views carry every key at runtime; the narrowing is a constraint on what a selector may - // read, so hand them over as the declared shape. - const runSelector = () => selector(liveStateView as OnyxStateViewFor, previousView as OnyxStateViewFor | undefined); - let output: T; - let deps: readonly OnyxKey[]; - if (depsArray) { - output = runSelector(); - deps = depsArray; - } else { - const run = recordReads(runSelector); - output = run.output; - // Keep the previous array while the set is unchanged, so the effect below can tell by reference. - deps = lastSnapshot !== null && isSameKeySet(lastSnapshot.deps, run.keys) ? lastSnapshot.deps : [...run.keys]; - } + const {output, keys} = recordReads(() => selector(liveStateView, previousView)); + // Keep the previous array while the set is unchanged, so the effect below can tell by reference. + const deps = lastSnapshot !== null && isSameKeySet(lastSnapshot.deps, keys) ? lastSnapshot.deps : [...keys]; const readPreviousState = previousStateReadRef.current; const depValues = deps.map((dep) => onyxSubscriptionManager.getState(dep)); @@ -281,17 +227,17 @@ function useOnyxState(selecto const value = lastSnapshot !== null && selectorEquality(lastSnapshot.value, output) ? lastSnapshot.value : output; lastSnapshotRef.current = {value, selector, previousView, readPreviousState, deps, depValues}; return value; - }, [selector, selectorEquality, depsArray]); + }, [selector, selectorEquality]); const value = useSyncExternalStore(subscribe, getSnapshot); - // Auto-tracking: move the subscription to the keys the latest run read. It runs after the commit, so a + // Move the subscription to the keys the latest run read. It runs after the commit, so a // write that landed in between on a newly read key fired nobody; comparing the values the run saw with // the current ones catches it, the same check React does when it first subscribes. useEffect(() => { const subscription = subscriptionRef.current; const lastSnapshot = lastSnapshotRef.current; - if (depsArray !== undefined || subscription === null || lastSnapshot === null || subscription.keys === lastSnapshot.deps) { + if (subscription === null || lastSnapshot === null || subscription.keys === lastSnapshot.deps) { return; } subscription.unsubscribe(); @@ -309,14 +255,14 @@ function useOnyxState(selecto // only on output changes also keeps a re-render from a parent from allocating a new view. useEffect(() => { const currentDepValues: Record> = {}; - for (const dep of depsArray ?? lastSnapshotRef.current?.deps ?? []) { + for (const dep of lastSnapshotRef.current?.deps ?? []) { currentDepValues[dep] = onyxSubscriptionManager.getState(dep); } previousViewRef.current = createStateView((key) => { previousStateReadRef.current = true; return currentDepValues[key]; }); - }, [value, depsArray]); + }, [value]); return value; } diff --git a/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx b/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx index 211b204df..aa76bc092 100644 --- a/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx +++ b/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx @@ -5,14 +5,11 @@ import React from 'react'; import {Text, View} from 'react-native'; import {measureRenders} from 'reassure'; -import type {OnyxKey} from '../../lib'; import type {OnyxStateView} from '../../lib/useOnyxState'; import Onyx from '../../lib'; import useOnyxState from '../../lib/useOnyxState'; -/** `collection` declares `report_`, `member` hand-declares `report_`, `auto` omits `dependencies`. */ -const MODE = (process.env.UOS_DEPS ?? 'auto') as 'collection' | 'member' | 'auto'; const COLLECTION_KEY = 'report_'; const UPDATES = 5; @@ -27,22 +24,12 @@ const seedCollection = async (size: number) => { let selectorRuns = 0; -function depsFor(key: OnyxKey) { - if (MODE === 'collection') { - return {dependencies: [COLLECTION_KEY] as OnyxKey[]}; - } - if (MODE === 'member') { - return {dependencies: [key]}; - } - return undefined; -} - function Row({index}: {index: number}) { const key = memberKey(index); const name = useOnyxState((state: OnyxStateView) => { selectorRuns++; return (state[key] as Report | undefined)?.name; - }, depsFor(key)); + }); return {`row ${index}: ${name ?? ''}`}; } @@ -60,13 +47,10 @@ function Rows({count}: {count: number}) { } function CollectionCount() { - const count = useOnyxState( - (state: OnyxStateView) => { - selectorRuns++; - return Object.keys((state[COLLECTION_KEY] as Record | undefined) ?? {}).length; - }, - MODE === 'auto' ? undefined : {dependencies: [COLLECTION_KEY] as OnyxKey[]}, - ); + const count = useOnyxState((state: OnyxStateView) => { + selectorRuns++; + return Object.keys((state[COLLECTION_KEY] as Record | undefined) ?? {}).length; + }); return {`count: ${count}`}; } @@ -98,7 +82,7 @@ describe('useOnyxState auto-tracked deps (issue 3020)', () => { afterAll(() => { const output = process.env.UPDATE_TIMINGS_FILE; if (output) { - fs.writeFileSync(output, JSON.stringify({mode: MODE, stats})); + fs.writeFileSync(output, JSON.stringify({stats})); } }); diff --git a/tests/types/useOnyxState.ts b/tests/types/useOnyxState.ts index a435e94a8..83477b07a 100644 --- a/tests/types/useOnyxState.ts +++ b/tests/types/useOnyxState.ts @@ -2,127 +2,72 @@ import useOnyxState from '../../dist/useOnyxState'; import ONYX_KEYS from './setup'; function readCollectionRoot() { - return useOnyxState( - (state) => { - const collection = state[ONYX_KEYS.COLLECTION.TEST_KEY]; - - if (!collection) { - return undefined; - } - - // A root reads back as the whole collection, so it is indexable by member key. - const draft: typeof collection = {...collection}; - draft.test_1 = {str: 'mutated'}; - - return draft; - }, - {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}, - ); + return useOnyxState((state) => { + const collection = state[ONYX_KEYS.COLLECTION.TEST_KEY]; + + if (!collection) { + return undefined; + } + + // A root reads back as the whole collection, so it is indexable by member key. + const draft: typeof collection = {...collection}; + draft.test_1 = {str: 'mutated'}; + + return draft; + }); } function readCollectionMember() { - return useOnyxState( - (state) => { - const member = state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]; - - if (!member) { - return undefined; - } - - // Annotation pins the draft to the read type because a spread alone drops readonly modifiers. - const draft: typeof member = {...member, list: member.list ? [...member.list] : undefined}; - draft.str = 'mutated'; - draft.list?.push('appended'); - - return draft; - }, - {dependencies: [`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]}, - ); + return useOnyxState((state) => { + const member = state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]; + + if (!member) { + return undefined; + } + + // Annotation pins the draft to the read type because a spread alone drops readonly modifiers. + const draft: typeof member = {...member, list: member.list ? [...member.list] : undefined}; + draft.str = 'mutated'; + draft.list?.push('appended'); + + return draft; + }); } function readSingleKey() { - return useOnyxState((state) => state[ONYX_KEYS.TEST_KEY]?.toUpperCase(), {dependencies: [ONYX_KEYS.TEST_KEY]}); + return useOnyxState((state) => state[ONYX_KEYS.TEST_KEY]?.toUpperCase()); } function readPreviousState() { - return useOnyxState( - (state, previousState) => { - const current = state[ONYX_KEYS.COLLECTION.TEST_KEY]; - const previous = previousState?.[ONYX_KEYS.COLLECTION.TEST_KEY]; - - // Both sides are collections, so changed members can be found by reference. - return Object.keys(current ?? {}).filter((key) => current?.[key] !== previous?.[key]); - }, - {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}, - ); -} + return useOnyxState((state, previousState) => { + const current = state[ONYX_KEYS.COLLECTION.TEST_KEY]; + const previous = previousState?.[ONYX_KEYS.COLLECTION.TEST_KEY]; -function rootIsNotAMember() { - return useOnyxState( - (state) => { - // @ts-expect-error a root reads as the whole collection, so it is not one member - const member: {str: string} | undefined = state[ONYX_KEYS.COLLECTION.TEST_KEY]; - - return member; - }, - {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}, - ); + // Both sides are collections, so changed members can be found by reference. + return Object.keys(current ?? {}).filter((key) => current?.[key] !== previous?.[key]); + }); } -function memberIsNotACollection() { - return useOnyxState( - (state) => { - const member = state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]; - - // @ts-expect-error a member is one entry, not a collection keyed by member key - return member?.test_1; - }, - {dependencies: [`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]}, - ); -} - -function cannotReadAnUndeclaredSingleKey() { - return useOnyxState( - // @ts-expect-error the selector only gets the keys its dependencies declared - (state) => state[ONYX_KEYS.TEST_KEY], - {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}, - ); -} +function rootIsNotAMember() { + return useOnyxState((state) => { + // @ts-expect-error a root reads as the whole collection, so it is not one member + const member: {str: string} | undefined = state[ONYX_KEYS.COLLECTION.TEST_KEY]; -function cannotReadAnUndeclaredCollection() { - return useOnyxState( - // @ts-expect-error the selector only gets the keys its dependencies declared - (state) => state[ONYX_KEYS.COLLECTION.TEST_KEY], - {dependencies: [ONYX_KEYS.TEST_KEY]}, - ); + return member; + }); } -function cannotReadAnUndeclaredKeyFromPreviousState() { - return useOnyxState( - // @ts-expect-error previousState is narrowed to the declared keys too - (state, previousState) => previousState?.[ONYX_KEYS.COLLECTION.TEST_KEY], - {dependencies: [ONYX_KEYS.TEST_KEY]}, - ); -} +function memberIsNotACollection() { + return useOnyxState((state) => { + const member = state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]; -function aDeclaredRootGrantsItsMembers() { - return useOnyxState((state) => state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]?.str, {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}); + // @ts-expect-error a member is one entry, not a collection keyed by member key + return member?.test_1; + }); } -function autoTrackedReadsAnyKey() { +function readsAnyKey() { return useOnyxState((state) => `${state[ONYX_KEYS.TEST_KEY] ?? ''}${state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]?.str ?? ''}`); } -export { - readCollectionRoot, - readCollectionMember, - readSingleKey, - readPreviousState, - rootIsNotAMember, - memberIsNotACollection, - cannotReadAnUndeclaredSingleKey, - cannotReadAnUndeclaredCollection, - cannotReadAnUndeclaredKeyFromPreviousState, - aDeclaredRootGrantsItsMembers, - autoTrackedReadsAnyKey, -}; +export {readCollectionRoot, readCollectionMember, readSingleKey, readPreviousState, rootIsNotAMember, memberIsNotACollection, readsAnyKey}; diff --git a/tests/unit/useOnyxStateTest.tsx b/tests/unit/useOnyxStateTest.tsx index 3beaa0333..509ea9e6d 100644 --- a/tests/unit/useOnyxStateTest.tsx +++ b/tests/unit/useOnyxStateTest.tsx @@ -32,14 +32,14 @@ describe('useOnyxState', () => { it('should return the derived value from a single dependency', async () => { await Onyx.set(ONYXKEYS.TEST_KEY, 'hello'); - const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY], {dependencies: [ONYXKEYS.TEST_KEY]})); + const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY])); await act(async () => waitForPromisesToResolve()); expect(result.current).toEqual('hello'); }); it('should update when the dependency changes', async () => { - const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY], {dependencies: [ONYXKEYS.TEST_KEY]})); + const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY])); await act(async () => waitForPromisesToResolve()); await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'updated')); @@ -51,7 +51,7 @@ describe('useOnyxState', () => { let renderCount = 0; const {result} = renderHook(() => { renderCount += 1; - return useOnyxState((state) => state[ONYXKEYS.TEST_KEY], {dependencies: [ONYXKEYS.TEST_KEY]}); + return useOnyxState((state) => state[ONYXKEYS.TEST_KEY]); }); await act(async () => waitForPromisesToResolve()); @@ -64,9 +64,7 @@ describe('useOnyxState', () => { }); it('should re-run when any of multiple dependencies change', async () => { - const {result} = renderHook(() => - useOnyxState((state) => `${state[ONYXKEYS.TEST_KEY] ?? ''}-${state[ONYXKEYS.OTHER_TEST] ?? ''}`, {dependencies: [ONYXKEYS.TEST_KEY, ONYXKEYS.OTHER_TEST]}), - ); + const {result} = renderHook(() => useOnyxState((state) => `${state[ONYXKEYS.TEST_KEY] ?? ''}-${state[ONYXKEYS.OTHER_TEST] ?? ''}`)); await act(async () => waitForPromisesToResolve()); await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'a')); @@ -79,7 +77,7 @@ describe('useOnyxState', () => { describe('collection dependency', () => { it('should re-run when any member of a collection dependency changes', async () => { - const {result} = renderHook(() => useOnyxState((state) => Object.keys(state[COLLECTION] ?? {}).length, {dependencies: [COLLECTION]})); + const {result} = renderHook(() => useOnyxState((state) => Object.keys(state[COLLECTION] ?? {}).length)); await act(async () => waitForPromisesToResolve()); expect(result.current).toEqual(0); @@ -92,7 +90,7 @@ describe('useOnyxState', () => { }); it('should re-run on a mergeCollection write', async () => { - const {result} = renderHook(() => useOnyxState((state) => Object.keys(state[COLLECTION] ?? {}).length, {dependencies: [COLLECTION]})); + const {result} = renderHook(() => useOnyxState((state) => Object.keys(state[COLLECTION] ?? {}).length)); await act(async () => waitForPromisesToResolve()); await act(async () => Onyx.mergeCollection(COLLECTION, {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}} as GenericCollection)); @@ -105,13 +103,10 @@ describe('useOnyxState', () => { it('should pass undefined as previousState on the first selector run', async () => { const observed: Array = []; renderHook(() => - useOnyxState( - (state, previousState) => { - observed.push(previousState); - return state[ONYXKEYS.TEST_KEY]; - }, - {dependencies: [ONYXKEYS.TEST_KEY]}, - ), + useOnyxState((state, previousState) => { + observed.push(previousState); + return state[ONYXKEYS.TEST_KEY]; + }), ); await act(async () => waitForPromisesToResolve()); @@ -124,15 +119,12 @@ describe('useOnyxState', () => { let sawCurrentBWithPreviousA = false; renderHook(() => - useOnyxState( - (state, previousState) => { - if (state[ONYXKEYS.TEST_KEY] === 'b' && previousState?.[ONYXKEYS.TEST_KEY] === 'a') { - sawCurrentBWithPreviousA = true; - } - return state[ONYXKEYS.TEST_KEY]; - }, - {dependencies: [ONYXKEYS.TEST_KEY]}, - ), + useOnyxState((state, previousState) => { + if (state[ONYXKEYS.TEST_KEY] === 'b' && previousState?.[ONYXKEYS.TEST_KEY] === 'a') { + sawCurrentBWithPreviousA = true; + } + return state[ONYXKEYS.TEST_KEY]; + }), ); await act(async () => waitForPromisesToResolve()); @@ -150,16 +142,13 @@ describe('useOnyxState', () => { await Onyx.mergeCollection(COLLECTION, {[MEMBER_1]: {v: 1}, [MEMBER_2]: {v: 1}} as GenericCollection); const {result} = renderHook(() => - useOnyxState( - (state, previousState) => { - const current = (state[COLLECTION] ?? {}) as Record; - const previous = (previousState?.[COLLECTION] ?? {}) as Record; - return Object.keys(current) - .filter((memberKey) => current[memberKey] !== previous[memberKey]) - .sort(); - }, - {dependencies: [COLLECTION]}, - ), + useOnyxState((state, previousState) => { + const current = (state[COLLECTION] ?? {}) as Record; + const previous = (previousState?.[COLLECTION] ?? {}) as Record; + return Object.keys(current) + .filter((memberKey) => current[memberKey] !== previous[memberKey]) + .sort(); + }), ); await act(async () => waitForPromisesToResolve()); @@ -173,16 +162,13 @@ describe('useOnyxState', () => { await Onyx.mergeCollection(COLLECTION, {[MEMBER_1]: {v: 1}, [MEMBER_2]: {v: 1}} as GenericCollection); const {result} = renderHook(() => - useOnyxState( - (state, previousState) => { - const current = (state[COLLECTION] ?? {}) as Record; - const previous = (previousState?.[COLLECTION] ?? {}) as Record; - return Object.keys(current) - .filter((memberKey) => current[memberKey] !== previous[memberKey]) - .sort(); - }, - {dependencies: [COLLECTION]}, - ), + useOnyxState((state, previousState) => { + const current = (state[COLLECTION] ?? {}) as Record; + const previous = (previousState?.[COLLECTION] ?? {}) as Record; + return Object.keys(current) + .filter((memberKey) => current[memberKey] !== previous[memberKey]) + .sort(); + }), ); await act(async () => waitForPromisesToResolve()); @@ -198,7 +184,7 @@ describe('useOnyxState', () => { describe('selectorEquality', () => { it('should preserve the output reference when the new output is deep-equal (default equality)', async () => { - const {result} = renderHook(() => useOnyxState((state) => ({length: ((state[ONYXKEYS.TEST_KEY] as string) ?? '').length}), {dependencies: [ONYXKEYS.TEST_KEY]})); + const {result} = renderHook(() => useOnyxState((state) => ({length: ((state[ONYXKEYS.TEST_KEY] as string) ?? '').length}))); await act(async () => waitForPromisesToResolve()); await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'aa')); @@ -214,7 +200,6 @@ describe('useOnyxState', () => { it('should never update after the first value when a custom equality always returns true', async () => { const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY] ?? 'none', { - dependencies: [ONYXKEYS.TEST_KEY], selectorEquality: () => true, }), ); @@ -231,7 +216,6 @@ describe('useOnyxState', () => { it('should update when a custom equality reports the output changed', async () => { const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY] ?? 'none', { - dependencies: [ONYXKEYS.TEST_KEY], selectorEquality: (a, b) => a === b, }), ); @@ -247,7 +231,7 @@ describe('useOnyxState', () => { it('should not run the selector again when the component re-renders and no dependency changed', async () => { await Onyx.set(ONYXKEYS.TEST_KEY, 'hello'); const selector = jest.fn((state: OnyxStateView) => state[ONYXKEYS.TEST_KEY]); - const {result, rerender} = renderHook((_props: {renderID: number}) => useOnyxState(selector, {dependencies: [ONYXKEYS.TEST_KEY]}), {initialProps: {renderID: 0}}); + const {result, rerender} = renderHook((_props: {renderID: number}) => useOnyxState(selector), {initialProps: {renderID: 0}}); await act(async () => waitForPromisesToResolve()); const callCountAfterMount = selector.mock.calls.length; @@ -260,12 +244,9 @@ describe('useOnyxState', () => { it('should run the selector again when a re-render passes a new selector', async () => { await Onyx.set(ONYXKEYS.TEST_KEY, 'hello'); - const {result, rerender} = renderHook( - ({suffix}: {suffix: string}) => useOnyxState((state) => `${state[ONYXKEYS.TEST_KEY] as string}${suffix}`, {dependencies: [ONYXKEYS.TEST_KEY]}), - { - initialProps: {suffix: '!'}, - }, - ); + const {result, rerender} = renderHook(({suffix}: {suffix: string}) => useOnyxState((state) => `${state[ONYXKEYS.TEST_KEY] as string}${suffix}`), { + initialProps: {suffix: '!'}, + }); await act(async () => waitForPromisesToResolve()); rerender({suffix: '?'}); @@ -276,7 +257,7 @@ describe('useOnyxState', () => { it('should run the selector again on a re-render after a dependency changed', async () => { await Onyx.set(ONYXKEYS.TEST_KEY, 'hello'); const selector = jest.fn((state: OnyxStateView) => state[ONYXKEYS.TEST_KEY]); - const {result} = renderHook(() => useOnyxState(selector, {dependencies: [ONYXKEYS.TEST_KEY]})); + const {result} = renderHook(() => useOnyxState(selector)); await act(async () => waitForPromisesToResolve()); const callCountAfterMount = selector.mock.calls.length; @@ -291,9 +272,7 @@ describe('useOnyxState', () => { // `Function.length` stops counting at the first defaulted parameter, so this selector reports // an arity of 1 even though it reads `previousState`. const {result} = renderHook(() => - useOnyxState((state, previousState = undefined) => `${state[ONYXKEYS.TEST_KEY] as string}/${(previousState?.[ONYXKEYS.TEST_KEY] as string) ?? 'none'}`, { - dependencies: [ONYXKEYS.TEST_KEY], - }), + useOnyxState((state, previousState = undefined) => `${state[ONYXKEYS.TEST_KEY] as string}/${(previousState?.[ONYXKEYS.TEST_KEY] as string) ?? 'none'}`), ); await act(async () => waitForPromisesToResolve()); @@ -322,11 +301,7 @@ describe('useOnyxState', () => { await StorageMock.setItem(ONYXKEYS.TEST_KEY, 'from storage'); await StorageMock.setItem(ONYXKEYS.OTHER_TEST, 'other from storage'); - const {result} = renderHook(() => - useOnyxState((state) => [state[ONYXKEYS.TEST_KEY], state[ONYXKEYS.OTHER_TEST]].join('|'), { - dependencies: [ONYXKEYS.TEST_KEY, ONYXKEYS.OTHER_TEST], - }), - ); + const {result} = renderHook(() => useOnyxState((state) => [state[ONYXKEYS.TEST_KEY], state[ONYXKEYS.OTHER_TEST]].join('|'))); // Then the selector has only an empty state to work with, because `cache.hydrate()` // notifies nobody @@ -346,13 +321,10 @@ describe('useOnyxState', () => { await StorageMock.setItem(ONYXKEYS.TEST_KEY, 'from storage'); const {result} = renderHook(() => - useOnyxState( - (state, previousState) => ({ - previous: previousState?.[ONYXKEYS.TEST_KEY], - current: state[ONYXKEYS.TEST_KEY], - }), - {dependencies: [ONYXKEYS.TEST_KEY]}, - ), + useOnyxState((state, previousState) => ({ + previous: previousState?.[ONYXKEYS.TEST_KEY], + current: state[ONYXKEYS.TEST_KEY], + })), ); // When init hydrates the cache after the first committed render @@ -365,19 +337,7 @@ describe('useOnyxState', () => { }); }); - describe('auto-tracked dependencies', () => { - it('should return the value and update when a read key changes', async () => { - await Onyx.set(ONYXKEYS.TEST_KEY, 'hello'); - const {result} = renderHook(() => useOnyxState((state) => state[ONYXKEYS.TEST_KEY])); - await act(async () => waitForPromisesToResolve()); - - expect(result.current).toEqual('hello'); - - await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'updated')); - - expect(result.current).toEqual('updated'); - }); - + describe('key tracking', () => { it('should not run the selector when a sibling of the read member changes', async () => { await Onyx.mergeCollection(COLLECTION, {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}} as GenericCollection); const selector = jest.fn((state: OnyxStateView) => (state[MEMBER_1] as {id: number} | undefined)?.id); @@ -428,17 +388,6 @@ describe('useOnyxState', () => { expect(result.current).toEqual('value'); }); - it('should re-run on any member write when the selector reads the collection root', async () => { - const {result} = renderHook(() => useOnyxState((state) => Object.keys(state[COLLECTION] ?? {}).length)); - await act(async () => waitForPromisesToResolve()); - - await act(async () => Onyx.merge(MEMBER_1, {id: 1})); - expect(result.current).toEqual(1); - - await act(async () => Onyx.merge(MEMBER_2, {id: 2})); - expect(result.current).toEqual(2); - }); - it('should keep tracking per hook when several hooks are mounted', async () => { const {result} = renderHook(() => ({ first: useOnyxState((state) => state[ONYXKEYS.TEST_KEY]), @@ -452,15 +401,5 @@ describe('useOnyxState', () => { await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'a')); expect(result.current).toEqual({first: 'a', second: 'b'}); }); - - it('should expose the tracked keys through previousState after a change', async () => { - await Onyx.set(ONYXKEYS.TEST_KEY, 'first'); - const {result} = renderHook(() => useOnyxState((state, previousState) => `${previousState?.[ONYXKEYS.TEST_KEY] as string}->${state[ONYXKEYS.TEST_KEY] as string}`)); - await act(async () => waitForPromisesToResolve()); - - await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'second')); - - expect(result.current).toEqual('first->second'); - }); }); }); From 07d7dfd7b111b52c7f6534a4d5437edaf687b071 Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Wed, 18 Nov 2026 12:09:57 +0100 Subject: [PATCH 3/4] Move useOnyxState subscription on store change, build previousState from committed run --- lib/useOnyxState.ts | 64 +++++++++++++++++++++------------ tests/unit/useOnyxStateTest.tsx | 58 ++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 23 deletions(-) diff --git a/lib/useOnyxState.ts b/lib/useOnyxState.ts index b495aeb3f..d9eb2497d 100644 --- a/lib/useOnyxState.ts +++ b/lib/useOnyxState.ts @@ -88,9 +88,10 @@ type SnapshotCache = { }; type StateSubscription = { - onStoreChange: () => void; keys: readonly OnyxKey[]; unsubscribe: () => void; + /** Moves the subscription to the keys the latest selector run read. */ + syncKeys: () => void; }; /** Runs the selector with `liveStateView` recording, and returns the set of keys it read. */ @@ -165,9 +166,33 @@ function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStat // Only `subscribe` has to be referentially stable, since it controls re-subscription. // `getSnapshot` may change identity freely, so it closes over the latest selector directly. const subscribe = useCallback((onStoreChange: () => void) => { + // React's store-change handler calls `getSnapshot` synchronously, so once it returns the latest + // run's keys are in `lastSnapshotRef`. Moving the subscription here rather than only after a + // commit matters when a run reads a new key but returns an equal output: nothing commits then. + const handleStoreChange = () => { + onStoreChange(); + subscription.syncKeys(); + }; + // React subscribes after the commit, so the snapshot behind the committed value is already there. const keys = lastSnapshotRef.current?.deps ?? []; - const subscription: StateSubscription = {onStoreChange, keys, unsubscribe: onyxSubscriptionManager.subscribeState(onStoreChange, keys)}; + const subscription: StateSubscription = { + keys, + unsubscribe: onyxSubscriptionManager.subscribeState(handleStoreChange, keys), + syncKeys: () => { + const lastSnapshot = lastSnapshotRef.current; + if (lastSnapshot === null || subscription.keys === lastSnapshot.deps) { + return; + } + subscription.unsubscribe(); + subscription.keys = lastSnapshot.deps; + subscription.unsubscribe = onyxSubscriptionManager.subscribeState(handleStoreChange, lastSnapshot.deps); + // A write that landed on a newly read key before this point fired nobody. + if (!areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues)) { + handleStoreChange(); + } + }, + }; subscriptionRef.current = subscription; // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it @@ -180,7 +205,7 @@ function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStat if (!isActive) { return; } - onStoreChange(); + handleStoreChange(); }); } @@ -230,39 +255,32 @@ function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStat }, [selector, selectorEquality]); const value = useSyncExternalStore(subscribe, getSnapshot); + // The run behind `value`. A store change between the commit and the effects below can overwrite the ref. + const renderedSnapshot = lastSnapshotRef.current; - // Move the subscription to the keys the latest run read. It runs after the commit, so a - // write that landed in between on a newly read key fired nobody; comparing the values the run saw with - // the current ones catches it, the same check React does when it first subscribes. + // A render can run the selector without a store change, say with a new selector, so the keys can move here too. useEffect(() => { - const subscription = subscriptionRef.current; - const lastSnapshot = lastSnapshotRef.current; - if (subscription === null || lastSnapshot === null || subscription.keys === lastSnapshot.deps) { - return; - } - subscription.unsubscribe(); - subscription.keys = lastSnapshot.deps; - subscription.unsubscribe = onyxSubscriptionManager.subscribeState(subscription.onStoreChange, lastSnapshot.deps); - if (!areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues)) { - subscription.onStoreChange(); - } + subscriptionRef.current?.syncKeys(); }); // Snapshot the deps after a commit that changed the output, to serve as `previousState` on the next // selector run. Doing it here rather than in `getSnapshot` keeps that function pure and gives // `previousState` its meaning, the deps behind the last committed output: a change whose output // the equality check swallowed never commits, so it never advances past a value nobody saw. Running - // only on output changes also keeps a re-render from a parent from allocating a new view. + // only on output changes also keeps a re-render from a parent from allocating a new view. The values + // come from the committed run, not the store, so a write landing before this effect still reads as a change. useEffect(() => { - const currentDepValues: Record> = {}; - for (const dep of lastSnapshotRef.current?.deps ?? []) { - currentDepValues[dep] = onyxSubscriptionManager.getState(dep); + const committedDepValues: Record> = {}; + if (renderedSnapshot !== null) { + for (const [index, dep] of renderedSnapshot.deps.entries()) { + committedDepValues[dep] = renderedSnapshot.depValues[index]; + } } previousViewRef.current = createStateView((key) => { previousStateReadRef.current = true; - return currentDepValues[key]; + return committedDepValues[key]; }); - }, [value]); + }, [value]); // eslint-disable-line react-hooks/exhaustive-deps return value; } diff --git a/tests/unit/useOnyxStateTest.tsx b/tests/unit/useOnyxStateTest.tsx index 509ea9e6d..15e15a528 100644 --- a/tests/unit/useOnyxStateTest.tsx +++ b/tests/unit/useOnyxStateTest.tsx @@ -1,4 +1,5 @@ import {act, renderHook} from '@testing-library/react-native'; +import {useLayoutEffect} from 'react'; import type {OnyxStateView} from '../../lib/useOnyxState'; import type GenericCollection from '../utils/GenericCollection'; @@ -401,5 +402,62 @@ describe('useOnyxState', () => { await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'a')); expect(result.current).toEqual({first: 'a', second: 'b'}); }); + + it('should start listening to a newly read key when the output stays the same', async () => { + // Given a branch that reads OTHER_TEST only once TEST_KEY is 'on', and returns null either way + await Onyx.set(ONYXKEYS.TEST_KEY, 'off'); + const {result} = renderHook(() => useOnyxState((state) => (state[ONYXKEYS.TEST_KEY] === 'on' ? (state[ONYXKEYS.OTHER_TEST] ?? null) : null))); + await act(async () => waitForPromisesToResolve()); + + // When the branch flips without changing the output, so nothing re-renders + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'on')); + expect(result.current).toBeNull(); + + // Then a write to the newly read key still reaches the hook + await act(async () => Onyx.set(ONYXKEYS.OTHER_TEST, 'value')); + expect(result.current).toEqual('value'); + }); + + it('should follow a pointer that arrives before the record it points at', async () => { + // Given a selector that looks up a member through a pointer key, with neither stored yet + const {result} = renderHook(() => + useOnyxState((state) => (state[ONYXKEYS.TEST_KEY] ? ((state[`${COLLECTION}${state[ONYXKEYS.TEST_KEY] as string}`] as {name: string} | undefined)?.name ?? null) : null)), + ); + await act(async () => waitForPromisesToResolve()); + + // When the pointer lands first, the output stays null + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, '1')); + expect(result.current).toBeNull(); + + // Then the record it points at still updates the hook when it arrives + await act(async () => Onyx.merge(MEMBER_1, {name: 'one'})); + expect(result.current).toEqual('one'); + }); + }); + + describe('previousState after a write between commit and effects', () => { + it('should keep the values the committed run saw, not a later write', async () => { + // Given a selector that reports the previous and current value of TEST_KEY + await Onyx.set(ONYXKEYS.TEST_KEY, 'a'); + const {result} = renderHook(() => { + const value = useOnyxState((state, previousState) => `${previousState?.[ONYXKEYS.TEST_KEY] as string}->${state[ONYXKEYS.TEST_KEY] as string}`); + // Layout effects run after the commit but before passive effects, which is where the hook builds previousState + useLayoutEffect(() => { + if (value !== 'a->b') { + return; + } + Onyx.set(ONYXKEYS.TEST_KEY, 'c'); + }, [value]); + return value; + }); + await act(async () => waitForPromisesToResolve()); + + // When 'b' commits and 'c' is written before the passive effects run + await act(async () => Onyx.set(ONYXKEYS.TEST_KEY, 'b')); + await act(async () => waitForPromisesToResolve()); + + // Then previousState holds 'b', the value behind the committed output, so the b->c change is not lost + expect(result.current).toEqual('b->c'); + }); }); }); From be313c91ef76fce7c2f369e118e3da7c845e42fe Mon Sep 17 00:00:00 2001 From: Hubert Sosinski Date: Wed, 18 Nov 2026 12:35:47 +0100 Subject: [PATCH 4/4] Simplify useOnyxState subscription handling --- lib/useOnyxState.ts | 75 +++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 44 deletions(-) diff --git a/lib/useOnyxState.ts b/lib/useOnyxState.ts index d9eb2497d..7f86ff53c 100644 --- a/lib/useOnyxState.ts +++ b/lib/useOnyxState.ts @@ -87,13 +87,6 @@ type SnapshotCache = { depValues: Array>; }; -type StateSubscription = { - keys: readonly OnyxKey[]; - unsubscribe: () => void; - /** Moves the subscription to the keys the latest selector run read. */ - syncKeys: () => void; -}; - /** Runs the selector with `liveStateView` recording, and returns the set of keys it read. */ function recordReads(run: () => T): {output: T; keys: Set} { const keys = new Set(); @@ -161,60 +154,54 @@ function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStat // `getSnapshot` calls and every one of them computes the same output. const previousViewRef = useRef(undefined); const lastSnapshotRef = useRef | null>(null); - const subscriptionRef = useRef(null); + const syncKeysRef = useRef<(() => void) | null>(null); // Only `subscribe` has to be referentially stable, since it controls re-subscription. // `getSnapshot` may change identity freely, so it closes over the latest selector directly. const subscribe = useCallback((onStoreChange: () => void) => { + let isActive = true; + // React subscribes after the commit, so the snapshot behind the committed value is already there. + let keys = lastSnapshotRef.current?.deps ?? []; + let unsubscribe = onyxSubscriptionManager.subscribeState(handleStoreChange, keys); + + /** Moves the subscription to the keys the latest selector run read. */ + function syncKeys() { + const lastSnapshot = lastSnapshotRef.current; + if (!isActive || lastSnapshot === null || keys === lastSnapshot.deps) { + return; + } + unsubscribe(); + keys = lastSnapshot.deps; + unsubscribe = onyxSubscriptionManager.subscribeState(handleStoreChange, keys); + // A write that landed on a newly read key before this point fired nobody. + if (!areDepValuesUnchanged(keys, lastSnapshot.depValues)) { + handleStoreChange(); + } + } + // React's store-change handler calls `getSnapshot` synchronously, so once it returns the latest // run's keys are in `lastSnapshotRef`. Moving the subscription here rather than only after a // commit matters when a run reads a new key but returns an equal output: nothing commits then. - const handleStoreChange = () => { + function handleStoreChange() { + if (!isActive) { + return; + } onStoreChange(); - subscription.syncKeys(); - }; - - // React subscribes after the commit, so the snapshot behind the committed value is already there. - const keys = lastSnapshotRef.current?.deps ?? []; - const subscription: StateSubscription = { - keys, - unsubscribe: onyxSubscriptionManager.subscribeState(handleStoreChange, keys), - syncKeys: () => { - const lastSnapshot = lastSnapshotRef.current; - if (lastSnapshot === null || subscription.keys === lastSnapshot.deps) { - return; - } - subscription.unsubscribe(); - subscription.keys = lastSnapshot.deps; - subscription.unsubscribe = onyxSubscriptionManager.subscribeState(handleStoreChange, lastSnapshot.deps); - // A write that landed on a newly read key before this point fired nobody. - if (!areDepValuesUnchanged(lastSnapshot.deps, lastSnapshot.depValues)) { - handleStoreChange(); - } - }, - }; - subscriptionRef.current = subscription; + syncKeys(); + } + syncKeysRef.current = syncKeys; // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it // finished saw an empty state and would never hear the stored values arrive. Re-read once // init lands. const initTask = OnyxUtils.getDeferredInitTask(); - let isActive = true; if (!initTask.isResolved) { - initTask.promise.then(() => { - if (!isActive) { - return; - } - handleStoreChange(); - }); + initTask.promise.then(handleStoreChange); } return () => { isActive = false; - subscription.unsubscribe(); - if (subscriptionRef.current === subscription) { - subscriptionRef.current = null; - } + unsubscribe(); }; }, []); @@ -260,7 +247,7 @@ function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStat // A render can run the selector without a store change, say with a new selector, so the keys can move here too. useEffect(() => { - subscriptionRef.current?.syncKeys(); + syncKeysRef.current?.(); }); // Snapshot the deps after a commit that changed the output, to serve as `previousState` on the next