11import { deepEqual } from 'fast-equals' ;
2- import { useCallback , useEffect , useMemo , useRef , useSyncExternalStore } from 'react' ;
2+ import { useCallback , useEffect , useRef , useSyncExternalStore } from 'react' ;
33
44import type { CollectionKeyBase , KeyValueMapping , OnyxCollection , OnyxKey , OnyxValue } from './types' ;
55
@@ -32,39 +32,9 @@ type OnyxStateView = {
3232 readonly [ K in OnyxKey ] : OnyxValue < K > ;
3333} & OnyxCollectionRootsView ;
3434
35- /** Declaring a collection root also grants its members: any member write fires the root. */
36- type DeclaredKeys < TDependency extends OnyxKey > = TDependency extends CollectionKeyBase ? TDependency | `${TDependency } ${string } ` : TDependency ;
37-
38- /**
39- * The state view a selector gets, holding only the keys its `dependencies` declared. Reading anything
40- * else is the bug this prevents: the key has no listener, and the snapshot cache skips the selector
41- * while the declared deps keep their references, so the value would sit there stale.
42- *
43- * Collection roots are spelled out a second time for the reason `OnyxCollectionRootsView` exists, and
44- * the whole thing falls back to the full view when the dependency list is not a literal, since there
45- * is then nothing to narrow to.
46- */
47- type OnyxStateViewFor < TDependencies extends readonly OnyxKey [ ] > = OnyxKey extends TDependencies [ number ]
48- ? OnyxStateView
49- : {
50- readonly [ K in DeclaredKeys < TDependencies [ number ] > ] : OnyxValue < K > ;
51- } & {
52- readonly [ K in Extract < TDependencies [ number ] , CollectionKeyBase > ] : OnyxCollection < KeyValueMapping [ K ] > ;
53- } ;
54-
55- type UseOnyxStateSelector < T , TDependencies extends readonly OnyxKey [ ] = readonly OnyxKey [ ] > = (
56- state : OnyxStateViewFor < TDependencies > ,
57- previousState : OnyxStateViewFor < TDependencies > | undefined ,
58- ) => T ;
59-
60- type UseOnyxStateOptions < T , TDependencies extends readonly OnyxKey [ ] = readonly OnyxKey [ ] > = {
61- /**
62- * Keys the selector reads. It re-runs when one of them changes; a collection key counts as a
63- * single dep, so any member change triggers a re-run. The selector's `state` only carries these
64- * keys, so reading anything else is a type error rather than a value that silently goes stale.
65- */
66- dependencies : TDependencies ;
35+ type UseOnyxStateSelector < T > = ( state : OnyxStateView , previousState : OnyxStateView | undefined ) => T ;
6736
37+ type UseOnyxStateOptions < T > = {
6838 /**
6939 * Equality for the selector's output. Defaults to `===` with a deep-equal fallback for objects.
7040 * When it returns true, the React update is skipped.
@@ -98,17 +68,41 @@ function createStateView(snapshotProvider: (key: OnyxKey) => OnyxValue<OnyxKey>)
9868 return new Proxy < Record < string , never > > ( { } , handler ) as unknown as OnyxStateView ;
9969}
10070
101- const liveStateView = createStateView ( ( key ) => onyxSubscriptionManager . getState ( key as OnyxKey ) ) ;
71+ /** Collects the keys the running selector reads from `liveStateView`, `null` when nothing is recording. */
72+ let activeRecorder : Set < OnyxKey > | null = null ;
73+
74+ const liveStateView = createStateView ( ( key ) => {
75+ activeRecorder ?. add ( key as OnyxKey ) ;
76+ return onyxSubscriptionManager . getState ( key as OnyxKey ) ;
77+ } ) ;
10278
103- type SnapshotCache < T , TDependencies extends readonly OnyxKey [ ] > = {
79+ type SnapshotCache < T > = {
10480 value : T ;
105- selector : UseOnyxStateSelector < T , TDependencies > ;
81+ selector : UseOnyxStateSelector < T > ;
10682 previousView : OnyxStateView | undefined ;
10783 /** Whether the run that produced `value` read `previousState`. A run that ignored it can't care that it moved. */
10884 readPreviousState : boolean ;
85+ /** The keys the run read. Same reference while the set is unchanged. */
86+ deps : readonly OnyxKey [ ] ;
10987 depValues : Array < OnyxValue < OnyxKey > > ;
11088} ;
11189
90+ /** Runs the selector with `liveStateView` recording, and returns the set of keys it read. */
91+ function recordReads < T > ( run : ( ) => T ) : { output : T ; keys : Set < OnyxKey > } {
92+ const keys = new Set < OnyxKey > ( ) ;
93+ const outerRecorder = activeRecorder ;
94+ activeRecorder = keys ;
95+ try {
96+ return { output : run ( ) , keys} ;
97+ } finally {
98+ activeRecorder = outerRecorder ;
99+ }
100+ }
101+
102+ function isSameKeySet ( keys : readonly OnyxKey [ ] , recorded : Set < OnyxKey > ) : boolean {
103+ return keys . length === recorded . size && keys . every ( ( key ) => recorded . has ( key ) ) ;
104+ }
105+
112106/** True when every dep still reads as the same reference it had when `depValues` was taken. */
113107function areDepValuesUnchanged ( deps : readonly OnyxKey [ ] , depValues : Array < OnyxValue < OnyxKey > > ) : boolean {
114108 if ( deps . length !== depValues . length ) {
@@ -138,59 +132,78 @@ function defaultSelectorEquality<T>(a: T, b: T): boolean {
138132
139133/**
140134 * Subscribes a component to a value derived from several Onyx keys. The selector gets a `state` view
141- * and a `previousState` view holding the declared deps as of the last committed render. It can use
135+ * and a `previousState` view holding the keys it read as of the last committed render. It can use
142136 * `previousState` to walk only what changed (structural sharing keeps unchanged collection members
143137 * reference-equal, so each step is O(1)) or as a real input, say to emit a delta.
144138 *
145- * Re-runs when any declared dep changes, and skips the React update when the output is equal to the
146- * previous one, per `selectorEquality`.
139+ * Each selector run records the keys it read from `state`, and the hook subscribes to exactly those.
140+ * A run's output depends only on what it read, so a key it skipped can't change it until a key it did
141+ * read changes and the selector runs again. Reading `report_1` subscribes to that member only, while
142+ * reading the `report_` root subscribes to every member.
143+ *
144+ * Skips the React update when the output is equal to the previous one, per `selectorEquality`.
147145 *
148146 * Mounting before `Onyx.init` has hydrated runs the selector against an empty state and re-runs it
149147 * once init lands. There is no status channel, so a consumer that must tell "not hydrated yet" from
150148 * "absent" has to carry that in its own output.
151149 */
152- function useOnyxState < T , const TDependencies extends readonly OnyxKey [ ] > ( selector : UseOnyxStateSelector < T , TDependencies > , options : UseOnyxStateOptions < T , TDependencies > ) : T {
153- const { dependencies , selectorEquality = defaultSelectorEquality } = options ;
150+ function useOnyxState < T > ( selector : UseOnyxStateSelector < T > , options : UseOnyxStateOptions < T > = { } ) : T {
151+ const { selectorEquality = defaultSelectorEquality } = options ;
154152
155- // Consumers pass an inline array literal, so key the memo on the contents: `depsArray` only gets
156- // a new reference when the set of keys changes, which keeps `subscribe` from re-subscribing on
157- // every render. The space separator is safe, Onyx keys never contain spaces. React Compiler
158- // can't preserve content-keying, so this hook opts out of it and memoizes by hand.
159- const depsKey = dependencies . join ( ' ' ) ;
160- const depsArray = useMemo ( ( ) => [ ...dependencies ] , [ depsKey ] ) ; // eslint-disable-line react-hooks/exhaustive-deps, react-hooks/preserve-manual-memoization
153+ // Mutated only in the post-commit effect below, so it stays frozen across a render's
154+ // `getSnapshot` calls and every one of them computes the same output.
155+ const previousViewRef = useRef < OnyxStateView | undefined > ( undefined ) ;
156+ const lastSnapshotRef = useRef < SnapshotCache < T > | null > ( null ) ;
157+ const syncKeysRef = useRef < ( ( ) => void ) | null > ( null ) ;
161158
162159 // Only `subscribe` has to be referentially stable, since it controls re-subscription.
163160 // `getSnapshot` may change identity freely, so it closes over the latest selector directly.
164- const subscribe = useCallback (
165- ( onStoreChange : ( ) => void ) => {
166- const unsubscribe = onyxSubscriptionManager . subscribeState ( onStoreChange , depsArray ) ;
167-
168- // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it
169- // finished saw an empty state and would never hear the stored values arrive. Re-read once
170- // init lands.
171- const initTask = OnyxUtils . getDeferredInitTask ( ) ;
172- let isActive = true ;
173- if ( ! initTask . isResolved ) {
174- initTask . promise . then ( ( ) => {
175- if ( ! isActive ) {
176- return ;
177- }
178- onStoreChange ( ) ;
179- } ) ;
161+ const subscribe = useCallback ( ( onStoreChange : ( ) => void ) => {
162+ let isActive = true ;
163+ // React subscribes after the commit, so the snapshot behind the committed value is already there.
164+ let keys = lastSnapshotRef . current ?. deps ?? [ ] ;
165+ let unsubscribe = onyxSubscriptionManager . subscribeState ( handleStoreChange , keys ) ;
166+
167+ /** Moves the subscription to the keys the latest selector run read. */
168+ function syncKeys ( ) {
169+ const lastSnapshot = lastSnapshotRef . current ;
170+ if ( ! isActive || lastSnapshot === null || keys === lastSnapshot . deps ) {
171+ return ;
172+ }
173+ unsubscribe ( ) ;
174+ keys = lastSnapshot . deps ;
175+ unsubscribe = onyxSubscriptionManager . subscribeState ( handleStoreChange , keys ) ;
176+ // A write that landed on a newly read key before this point fired nobody.
177+ if ( ! areDepValuesUnchanged ( keys , lastSnapshot . depValues ) ) {
178+ handleStoreChange ( ) ;
180179 }
180+ }
181181
182- return ( ) => {
183- isActive = false ;
184- unsubscribe ( ) ;
185- } ;
186- } ,
187- [ depsArray ] ,
188- ) ;
182+ // React's store-change handler calls `getSnapshot` synchronously, so once it returns the latest
183+ // run's keys are in `lastSnapshotRef`. Moving the subscription here rather than only after a
184+ // commit matters when a run reads a new key but returns an equal output: nothing commits then.
185+ function handleStoreChange ( ) {
186+ if ( ! isActive ) {
187+ return ;
188+ }
189+ onStoreChange ( ) ;
190+ syncKeys ( ) ;
191+ }
192+ syncKeysRef . current = syncKeys ;
189193
190- // Mutated only in the post-commit effect below, so it stays frozen across a render's
191- // `getSnapshot` calls and every one of them computes the same output.
192- const previousViewRef = useRef < OnyxStateView | undefined > ( undefined ) ;
193- const lastSnapshotRef = useRef < SnapshotCache < T , TDependencies > | null > ( null ) ;
194+ // `Onyx.init` hydrates the cache without notifying anyone, so a selector that ran before it
195+ // finished saw an empty state and would never hear the stored values arrive. Re-read once
196+ // init lands.
197+ const initTask = OnyxUtils . getDeferredInitTask ( ) ;
198+ if ( ! initTask . isResolved ) {
199+ initTask . promise . then ( handleStoreChange ) ;
200+ }
201+
202+ return ( ) => {
203+ isActive = false ;
204+ unsubscribe ( ) ;
205+ } ;
206+ } , [ ] ) ;
194207
195208 // Flipped by the `previousState` view when the selector reads a key off it. Read straight after the
196209 // selector returns, so it describes that run only.
@@ -209,42 +222,52 @@ function useOnyxState<T, const TDependencies extends readonly OnyxKey[]>(selecto
209222 lastSnapshot !== null &&
210223 lastSnapshot . selector === selector &&
211224 ( ! lastSnapshot . readPreviousState || lastSnapshot . previousView === previousView ) &&
212- areDepValuesUnchanged ( depsArray , lastSnapshot . depValues )
225+ areDepValuesUnchanged ( lastSnapshot . deps , lastSnapshot . depValues )
213226 ) {
214227 return lastSnapshot . value ;
215228 }
216229
217- const depValues = depsArray . map ( ( dep ) => onyxSubscriptionManager . getState ( dep ) ) ;
218230 previousStateReadRef . current = false ;
219- // The views carry every key at runtime; the narrowing is a constraint on what a selector may
220- // read , so hand them over as the declared shape .
221- const output = selector ( liveStateView as OnyxStateViewFor < TDependencies > , previousView as OnyxStateViewFor < TDependencies > | undefined ) ;
231+ const { output , keys } = recordReads ( ( ) => selector ( liveStateView , previousView ) ) ;
232+ // Keep the previous array while the set is unchanged , so the effect below can tell by reference .
233+ const deps = lastSnapshot !== null && isSameKeySet ( lastSnapshot . deps , keys ) ? lastSnapshot . deps : [ ... keys ] ;
222234 const readPreviousState = previousStateReadRef . current ;
235+ const depValues = deps . map ( ( dep ) => onyxSubscriptionManager . getState ( dep ) ) ;
223236
224237 // Hand back the previous reference when the output is equal, so React bails out via `===`
225238 // and an unchanged store keeps returning the same value even as `getSnapshot`'s identity moves.
226239 const value = lastSnapshot !== null && selectorEquality ( lastSnapshot . value , output ) ? lastSnapshot . value : output ;
227- lastSnapshotRef . current = { value, selector, previousView, readPreviousState, depValues} ;
240+ lastSnapshotRef . current = { value, selector, previousView, readPreviousState, deps , depValues} ;
228241 return value ;
229- } , [ selector , selectorEquality , depsArray ] ) ;
242+ } , [ selector , selectorEquality ] ) ;
230243
231244 const value = useSyncExternalStore ( subscribe , getSnapshot ) ;
245+ // The run behind `value`. A store change between the commit and the effects below can overwrite the ref.
246+ const renderedSnapshot = lastSnapshotRef . current ;
247+
248+ // A render can run the selector without a store change, say with a new selector, so the keys can move here too.
249+ useEffect ( ( ) => {
250+ syncKeysRef . current ?.( ) ;
251+ } ) ;
232252
233253 // Snapshot the deps after a commit that changed the output, to serve as `previousState` on the next
234254 // selector run. Doing it here rather than in `getSnapshot` keeps that function pure and gives
235255 // `previousState` its meaning, the deps behind the last committed output: a change whose output
236256 // the equality check swallowed never commits, so it never advances past a value nobody saw. Running
237- // only on output changes also keeps a re-render from a parent from allocating a new view.
257+ // only on output changes also keeps a re-render from a parent from allocating a new view. The values
258+ // come from the committed run, not the store, so a write landing before this effect still reads as a change.
238259 useEffect ( ( ) => {
239- const currentDepValues : Record < OnyxKey , OnyxValue < OnyxKey > > = { } ;
240- for ( const dep of depsArray ) {
241- currentDepValues [ dep ] = onyxSubscriptionManager . getState ( dep ) ;
260+ const committedDepValues : Record < OnyxKey , OnyxValue < OnyxKey > > = { } ;
261+ if ( renderedSnapshot !== null ) {
262+ for ( const [ index , dep ] of renderedSnapshot . deps . entries ( ) ) {
263+ committedDepValues [ dep ] = renderedSnapshot . depValues [ index ] ;
264+ }
242265 }
243266 previousViewRef . current = createStateView ( ( key ) => {
244267 previousStateReadRef . current = true ;
245- return currentDepValues [ key ] ;
268+ return committedDepValues [ key ] ;
246269 } ) ;
247- } , [ value , depsArray ] ) ;
270+ } , [ value ] ) ; // eslint-disable-line react-hooks/exhaustive-deps
248271
249272 return value ;
250273}
0 commit comments