diff --git a/lib/useOnyxState.ts b/lib/useOnyxState.ts index 604198775..7f86ff53c 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,39 +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. - */ - 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. @@ -98,17 +68,41 @@ function createStateView(snapshotProvider: (key: OnyxKey) => OnyxValue) return new Proxy>({}, handler) as unknown as OnyxStateView; } -const liveStateView = createStateView((key) => onyxSubscriptionManager.getState(key as OnyxKey)); +/** Collects the keys the running 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 = { +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 keys the run read. Same reference while the set is unchanged. */ + deps: readonly OnyxKey[]; depValues: Array>; }; +/** 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) { @@ -138,59 +132,78 @@ 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 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; +function useOnyxState(selector: UseOnyxStateSelector, options: UseOnyxStateOptions = {}): T { + const {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 + // 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 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) => { - const unsubscribe = onyxSubscriptionManager.subscribeState(onStoreChange, depsArray); - - // `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(); - }); + 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(); } + } - return () => { - isActive = false; - unsubscribe(); - }; - }, - [depsArray], - ); + // 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. + function handleStoreChange() { + if (!isActive) { + return; + } + onStoreChange(); + syncKeys(); + } + syncKeysRef.current = syncKeys; - // 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); + // `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(); + if (!initTask.isResolved) { + initTask.promise.then(handleStoreChange); + } + + return () => { + isActive = false; + unsubscribe(); + }; + }, []); // 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. @@ -209,42 +222,52 @@ function useOnyxState(selecto lastSnapshot !== null && lastSnapshot.selector === selector && (!lastSnapshot.readPreviousState || lastSnapshot.previousView === previousView) && - areDepValuesUnchanged(depsArray, lastSnapshot.depValues) + 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 {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)); // 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]); + }, [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; + + // A render can run the selector without a store change, say with a new selector, so the keys can move here too. + useEffect(() => { + syncKeysRef.current?.(); + }); // 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 depsArray) { - 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, depsArray]); + }, [value]); // eslint-disable-line react-hooks/exhaustive-deps return value; } diff --git a/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx b/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx new file mode 100644 index 000000000..aa76bc092 --- /dev/null +++ b/tests/perf-test/useOnyxStateAutoDeps.perf-test.tsx @@ -0,0 +1,135 @@ +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 {OnyxStateView} from '../../lib/useOnyxState'; + +import Onyx from '../../lib'; +import useOnyxState from '../../lib/useOnyxState'; + +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 Row({index}: {index: number}) { + const key = memberKey(index); + const name = useOnyxState((state: OnyxStateView) => { + selectorRuns++; + return (state[key] as Report | undefined)?.name; + }); + 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; + }); + 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({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..83477b07a 100644 --- a/tests/types/useOnyxState.ts +++ b/tests/types/useOnyxState.ts @@ -2,122 +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 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 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]}, - ); + return member; + }); } -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]}, - ); -} +function memberIsNotACollection() { + return useOnyxState((state) => { + const member = state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]; -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]}, - ); + // @ts-expect-error a member is one entry, not a collection keyed by member key + return member?.test_1; + }); } -function aDeclaredRootGrantsItsMembers() { - return useOnyxState((state) => state[`${ONYX_KEYS.COLLECTION.TEST_KEY}1`]?.str, {dependencies: [ONYX_KEYS.COLLECTION.TEST_KEY]}); +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, -}; +export {readCollectionRoot, readCollectionMember, readSingleKey, readPreviousState, rootIsNotAMember, memberIsNotACollection, readsAnyKey}; diff --git a/tests/unit/useOnyxStateTest.tsx b/tests/unit/useOnyxStateTest.tsx index 38f54bfaf..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'; @@ -32,14 +33,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 +52,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 +65,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 +78,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 +91,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 +104,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 +120,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 +143,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 +163,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 +185,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 +201,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 +217,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 +232,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 +245,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 +258,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 +273,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 +302,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 +322,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 @@ -364,4 +337,127 @@ describe('useOnyxState', () => { expect(result.current).toEqual({previous: undefined, current: 'from storage'}); }); }); + + 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); + 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 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 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'); + }); + }); });