Skip to content

Add useOnyxState multi-key derived state hook - #894

Open
sosek108 wants to merge 29 commits into
Expensify:mainfrom
callstack-internal:hubert/useonyxstate
Open

sosek108 wants to merge 29 commits into
Expensify:mainfrom
callstack-internal:hubert/useonyxstate

Conversation

@sosek108

@sosek108 sosek108 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Details

Adds useOnyxState, a hook that derives one value from any number of Onyx keys.

const total = useOnyxState((state) => state[`report_${reportID}`]?.total, {selectorEquality});
  • The selector gets a read-only state view. Reading a key returns the cached value, or the frozen snapshot for a collection root.
  • Dependencies are tracked automatically. Each run records the keys it read and the hook subscribes to exactly those. Reading report_1 subscribes to that member, reading report_ subscribes to the whole collection. When a branch or lookup reads a new key, the subscription moves to it.
  • The output goes through selectorEquality (default Object.is, then deepEqual for objects). An equal output keeps the old reference, so React skips the update. An output that is a value read straight from the store, such as state[key], is compared by reference only, the way useOnyx without a selector returns it.
  • On a re-render with the same selector and unchanged deps, the selector is not run again.
  • A hook mounted before Onyx.init hydrates re-runs once init lands.

OnyxSubscriptionManager gets a subscribeState index keyed by dependency. Each listener fires at most once per notifyKey/notifyCollection, even if both a member and its collection key match.

Exports useOnyxState and the OnyxStateView, UseOnyxStateOptions and UseOnyxStateSelector types. The README gets a useOnyxState() section.

A write that changes several non-collection keys one by one (Onyx.update, Onyx.multiSet) runs the selector once per changed key the hook reads, with one render. Making Onyx.update atomic (Expensify/App#101801) brings that down to one run.

Related Issues

$ Expensify/App#107492

Linked E/App PR

Expensify/App#107544

Automated Tests

  • tests/unit/useOnyxStateTest.tsx: single and multi-key updates, collection and mergeCollection writes, selectorEquality, selector skip on re-render, hydration after Onyx.init, and key tracking (sibling members, lookups, new branches, several hooks, new key with equal output).
  • tests/unit/OnyxSubscriptionManagerTest.ts: subscribeState fires on its deps only, once per dispatch, and cleans the index on unsubscribe.
  • tests/types/useOnyxState.ts: state types a collection root as the whole collection and a member as one entry.
  • tests/perf-test/useOnyxState.perf-test.tsx: Reassure renders for 100 and 1000 rows when one member or the collection changes.

Manual Tests

No App code calls useOnyxState yet. The steps below are a regression pass over the existing subscription paths (Onyx.connect, useOnyx), because OnyxSubscriptionManager and the way connect delivers values changed.

  1. Sign in and cold start
    • Sign in. Verify the LHN, the last opened report and the avatar load, with no infinite skeleton.
    • Kill and reopen the app. Verify the same screen comes back from cache before the network responds.
  2. Live report updates
    • Open a chat and send three messages quickly. Verify each appears once, in order, and the LHN preview shows the last one.
    • From a second account, send a message to the first. Verify it appears without a refresh, and the unread marker and the LHN bold state update.
    • Edit and delete a message. Verify the list and the LHN preview both update.
  3. Collection writes
    • Create an expense, then open the expense report. Verify the report total, the preview in the chat and the Reports row all match.
    • Change the amount. Verify all three update.
    • In a workspace, add a category and a tag. Verify they appear at once in the list and in the expense form picker.
  4. Flags that flip and reset
    • Go offline. Verify the offline indicator appears. Send a message and verify it shows as pending.
    • Go online. Verify the indicator goes away, the message stops being pending and nothing is duplicated.
    • Enter an invalid magic code. Verify the error shows, then clears when you retype.
    • Open a report that needs loading. Verify the loading skeleton ends.
  5. Settings
    • Change the preferred language and the theme. Verify the whole app updates without a reload.
    • Switch priority mode between Most Recent and #focus. Verify the LHN re-sorts.
  6. Sign out and account switch
    • Sign out. Verify you land on the sign-in page with no crash.
    • Sign in as a different account. Verify no data from the first account shows (LHN, workspaces, avatar).
  7. Multi-tab (web only)
    • Open two tabs. Send a message in one and verify it appears in the other.
    • Sign out in one tab. Verify the other signs out too.
  8. Verify there are no new console errors, in particular [OnyxSubscriptionManager] Listener threw an error.

Author Checklist

  • I linked the correct issue in the ### Related Issues section above
  • I linked the corresponding Expensify/App PR in the ### Linked E/App PR section above, and verified this change against it (E/App CI passed and manual testing completed)
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

fabioh8010 and others added 15 commits October 22, 2026 08:20
Adds a state-listener index to OnyxSubscriptionManager (subscribeState, dep-keyed, once-per-dispatch fire) and useOnyxState, a hook that derives a value from multiple Onyx keys with explicit dependencies and a previousState view.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`cache.hydrate()` fills the cache without notifying anyone, so a `useOnyxState`
subscriber that mounted during a cold start ran its selector against an empty
state and never heard the stored values arrive. It bites above the app's
migration gate — the providers wrapped around it, and `HybridAppHandler` — where
components render before Onyx has finished initialising.

`useOnyx` grew the same fix, but needed more than this: its `loading` flag lives
outside the `useSyncExternalStore` snapshot, so it also needed an availability
value in the snapshot to force a re-render for a key that init resolves to no
value at all. `useOnyxState` has no status channel, so React bailing out on an
unchanged selector output is the right outcome and the subscribe side is enough.

The flip side is that a consumer cannot tell "not hydrated yet" from "absent"
unless it encodes that in its own output. Said so in the hook's docblock rather
than inventing a status channel here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The file sat at 41% comments against 23% in useOnyx.ts and
OnyxSubscriptionManager.ts, and explained why `previousState` advances
post-commit in three separate places. That rationale now lives once, on the
effect that does it. Comments only, no behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Reading a collection root off the state view came back typed as a single member,
while at runtime it is the whole collection, so consumers had to cast.

Collection keys reach `OnyxKey` as the template `${CollectionKeyBase}${string}`,
and a mapped type turns that into one index signature typed off the template
rather than off the key being indexed. The template itself does not extend
`CollectionKeyBase`, so `OnyxValue` picks the member branch, and a root such as
`report_` matches the signature and inherits that member type.

Spelling the roots out in their own mapped type gives them a declared property,
which wins over the index signature. Without `CustomTypeOptions` the guard
resolves to `unknown` and the view is unchanged, since every key there is
already `unknown`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The snapshot cache skipped `previousState` for any selector whose
`Function.length` was 1. That misreads a selector written
`(state, previousState = undefined) => ...`, because `length` stops counting at
the first defaulted parameter: it reads `previousState` but would have been
handed `undefined` on every run, with no error.

The view itself now reports when the selector reads a key off it, and the cache
records whether the run that produced the value did so. A run that ignored
`previousState` can't be affected by it moving, so it still stays cached when
only the view changed. That keeps the saving without inferring anything from the
signature.

Selector runs, measured on 20 parent re-renders with no store change: a
`(state)` selector stays at 0, and a selector reading `previousState` goes from
2 to 0. Store writes and mount are unchanged at 10 and 1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Dependencies were declared by hand and nothing checked them, and the snapshot
cache made that worse: it skips the selector while every declared dep holds its
reference, so a key read but not declared stays stale instead of being picked up
by the next render.

The selector's state and previousState are now typed from the dependency list,
so reading anything else does not compile. Declaring a collection root still
grants its members, since any member write fires the root. A dependency list
that is not a literal, so there is nothing to narrow to, falls back to the full
view.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Auto-track useOnyxState keys, drop declared dependencies
@sosek108 sosek108 changed the title [WIP][POC] Add useOnyxState multi-key derived state hook [WIP] Add useOnyxState multi-key derived state hook Nov 20, 2026
@sosek108 sosek108 changed the title [WIP] Add useOnyxState multi-key derived state hook [WIP][No QA] Add useOnyxState multi-key derived state hook Nov 20, 2026
@lorretheboy

Copy link
Copy Markdown

Hi I am C+ of this project, comment here for C+ assignment once it is ready for review

@sosek108
sosek108 marked this pull request as ready for review November 23, 2026 09:39
@sosek108
sosek108 requested a review from a team as a code owner November 23, 2026 09:39
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T09:45:13.615929Z 48a7f6b Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@sosek108

Copy link
Copy Markdown
Contributor Author

@lorretheboy You can start reviewing this PR, thanks for patience

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48a7f6b55e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread lib/useOnyxState.ts Resolved
Comment thread lib/useOnyxState.ts Resolved
@sosek108 sosek108 changed the title [WIP][No QA] Add useOnyxState multi-key derived state hook [No QA] Add useOnyxState multi-key derived state hook Nov 25, 2026
Comment thread lib/OnyxSubscriptionManager.ts Outdated

/**
* Subscribe to state-tree changes. The listener fires when any of the dependency keys changes.
* A collection key counts as a single dep: any member change fires it. Used by `useOnyxState`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am a bit concerned about this because I think it results in the same problem we have today. If a major component subscribes to an entire collect (a popular collection with many changes), then it re-renders a lot, even if something in that collection wasn't directly used in rendering. For example, subscribing to the entire reports_ or workspace_ collections.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A member write re-runs the selector, but the component re-renders only when the output changes. The remaining cost is the selector run, so reading a member key like report_123 is cheaper when that's enough.

Comment thread lib/OnyxSubscriptionManager.ts Outdated
*/
subscribeState(listener: StateListenerCallback, deps: readonly OnyxKey[]): StateSubscription {
const entry: StateListenerEntry = {listener, deps: new Set(deps)};
let isSubscribed = true;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than tracking this separately, can it be deferred from the state entry? It seems like it would be the same thing, so we don't need two different ways to track it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, currentDeps is set to null on unsubscribe and replaces the flag.

Comment thread lib/OnyxSubscriptionManager.ts Outdated
Comment on lines +205 to +208
this.fireStateListenersForDep(key, fired);
if (isCollectionMemberWrite) {
this.fireStateListenersForDep(collectionKey, fired);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be more simple to write:

this.fireStateListenersForDep(isCollectionMemberWrite ? collectionKey : key, fired);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code was removed when we merged the two listener indexes per Rory's review.

Comment thread lib/OnyxSubscriptionManager.ts Outdated
return;
}

for (const entry of [...set]) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is set being destructured here? Is it really necessary?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Iterating a live Set also visits listeners added during the loop, so a listener that subscribes during dispatch would fire in the same pass. main copies for the same reason. Added a comment.

Comment thread lib/useOnyxState.ts
*/
function readAndRecord(key: OnyxKey): OnyxValue<OnyxKey> {
if (activeRecorder === null) {
throw new Error(`useOnyxState: "${key}" was read from the state view outside a selector. Read every key while the selector runs.`);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the selector returns a closure or getter that reads state lazily, or state is stashed and read in an effect or handler.

Are these valid scenarios? I don't think they are for the selectors

Comment thread lib/useOnyxState.ts Outdated
let keys = committedSnapshotterRef.current?.peek()?.deps ?? [];
const subscription = onyxSubscriptionManager.subscribeState(handleStoreChange, keys);

/** Moves the subscription to the keys the latest selector run read. */

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is hard to understand too

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rephrased.

Comment thread lib/useOnyxState.ts
}
keys = lastSnapshot.deps;
subscription.updateDeps(keys);
// A write that landed on a newly read key before this point fired nobody.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use a consistent format with comments. Sometimes it's // and other times it's /** ... */

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: /** */ for top-level declarations and type members, // inside function bodies.

Comment thread lib/useOnyxState.ts Outdated
}
onStoreChange();
// React's store-change handler has normally just run the committed `getSnapshot`, which makes
// this call a cached read. Running it here keeps the keys current without relying on that.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

without relying on that

It's not clear what "that" is referring to

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rephrased.

Comment thread lib/useOnyxState.ts
Comment on lines +235 to +238
// One snapshotter per selector. Its runs are cached in its own closure rather than in a ref shared
// by every render, because React can throw a render away (a suspended or interrupted transition).
// A shared ref would then hold the output of a selector that never reached the screen, and the next
// run would be compared against it instead of the committed value.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a really great comment ❤️

Comment thread README.md Outdated
* Read every key while the selector runs. Reading `state` later, for example from a function the selector returned, throws.
* `state` cannot be enumerated. `Object.keys(state)`, a spread or `for...in` throws. Read a collection key to get all its members.
* The output is compared with the previous one by `===`, then by deep equality for objects, and an equal output keeps the previous reference. Pass `selectorEquality` in the second argument to replace this. A value returned straight from the store, such as `state[key]`, is compared by reference only.
* The hook returns the value directly and has no `status`. Before `Onyx.init()` has loaded the stored data the selector sees an empty state, and runs again once the data is there.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because of this, it makes me think that every usage of useOnyxState() should always include if (state.isEmpty()) return;. Is that true?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. Before init every key reads as undefined, which a selector already handles for any missing key, and it re-runs once the data loads. Reworded the README so it doesn't read as a separate "empty" state.

@roryabraham roryabraham left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see that this implementation adds a second “index” in OnyxSubscriptionManager. Here’s how it works in the PR currently:

  • (existing) keyListeners tracks subscribers by key and calls them with (value, key). When a collection member changes, it notifies subscribers to both the exact key and the parent collection. Onyx.connect and useOnyx register here through subscribe.
  • (new) stateListenersByDep also tracks subscribers by key. useOnyxState registers through subscribeState, which can update the list of keys the selector depends on. The callback gets no payload: it reads from the cache and runs once per dispatch even when multiple dependencies match. These callbacks run after the key listeners.

This adds a fair bit of complexity. Can we simplify it?

  • Use one index and one subscribe method. A single-key subscription is just a subscription with one dependency. Every listener gets the same payload-free signal, so there’s no need for separate dispatch phases.
  • Have Onyx.connect read the value for its key from the cache when signaled. It still passes (value, key) to the caller. useOnyx already reads the cache and ignores the payload.

The public API stays the same, except for one subtle breaking change. Say two callbacks subscribe to the same status key, with callback A registered before callback B.

Before:

  1. A write sets the status to saving. Callback A receives saving and immediately writes saved to the same key.
  2. That second write notifies both callbacks before the first notification resumes. Callback B receives saved.
  3. The first notification resumes and calls B with its original saving payload. B sees saved and then saving, even though the cache holds saved.

After:

  1. A write sets the status to saving. Callback A reads saving from the cache and immediately writes saved.
  2. That second write signals both callbacks. Callback B reads saved from the cache and receives it.
  3. The first notification resumes. B reads saved again, so there’s no new value to deliver. B sees saved just once.

While this is technically a breaking change, it could also be framed as a bug fix. Before, subscriber B sees the correct value (saved) and then receives a stale value (saving). If B uses the callback to keep its own state in sync, it’s left showing saving even though the cache says saved. With this change, B is left with the correct value.

Vibe-coded diff
diff --git a/API.md b/API.md
index 82183ea0..2a4804c7 100644
--- a/API.md
+++ b/API.md
@@ -107,8 +107,10 @@ const connection = Onyx.connect({
 For a collection root key, the callback fires with the entire frozen collection
 object whenever any member changes; signature `(collection, collectionKey)`.
 For any other key, the callback fires with the value at that key; signature
-`(value, key)`. Initial fire is deferred via `scheduleInitialSubscriberNotification` so it reads
-cache after any same-tick writes have applied.
+`(value, key)`. The callback reads the latest snapshot and skips identical values. If another
+subscriber synchronously overwrites the key, later subscribers may not see the superseded
+value. `scheduleInitialSubscriberNotification` defers the initial cache read until relevant
+same-tick writes settle, without waiting for unrelated writes.
 &lt;a name="connectWithoutView"&gt;&lt;/a&gt;
&#32;
 ## connectWithoutView(connectOptions) ⇒
@@ -134,8 +136,10 @@ const connection = Onyx.connectWithoutView({
 For a collection root key, the callback fires with the entire frozen collection
 object whenever any member changes; signature `(collection, collectionKey)`.
 For any other key, the callback fires with the value at that key; signature
-`(value, key)`. Initial fire is deferred via `scheduleInitialSubscriberNotification` so it reads
-cache after any same-tick writes have applied.
+`(value, key)`. The callback reads the latest snapshot and skips identical values. If another
+subscriber synchronously overwrites the key, later subscribers may not see the superseded
+value. `scheduleInitialSubscriberNotification` defers the initial cache read until relevant
+same-tick writes settle, without waiting for unrelated writes.
 &lt;a name="set"&gt;&lt;/a&gt;
&#32;
 ## set(key, value, options)
diff --git a/README.md b/README.md
index 9dfc9bd0..2173b568 100644
--- a/README.md
+++ b/README.md
@@ -122,6 +122,8 @@ You should avoid arrays as much as possible. They do not work well with `merge()
&#32;
 To set up a basic subscription for a given key outside of a React component use the `Onyx.connectWithoutView()` method. It returns a connection handle.
&#32;
+`connectWithoutView()` and `connect()` deliver the latest cached value, not a stream of writes. If another subscriber synchronously overwrites the key, later callbacks can skip the superseded value. Use an explicit event stream if you need to observe every write.
+
 ```javascript
 let session;
 const connection = Onyx.connectWithoutView({
diff --git a/lib/Onyx.ts b/lib/Onyx.ts
index 6c79a8c2..c8c81f6a 100644
--- a/lib/Onyx.ts
+++ b/lib/Onyx.ts
@@ -4,11 +4,9 @@ import Storage from './storage';
 import utils from './utils';
 import DevTools, {initDevTools} from './DevTools';
 import type {
-    CollectionConnectCallback,
     CollectionKeyBase,
     Connection,
     ConnectOptions,
-    DefaultConnectCallback,
     InitOptions,
     KeyValueMapping,
     MixedOperationsQueue,
@@ -140,8 +138,10 @@ function init({
  * For a collection root key, the callback fires with the entire frozen collection
  * object whenever any member changes; signature `(collection, collectionKey)`.
  * For any other key, the callback fires with the value at that key; signature
- * `(value, key)`. Initial fire is deferred via `scheduleInitialSubscriberNotification` so it reads
- * cache after any same-tick writes have applied.
+ * `(value, key)`. The callback reads the latest snapshot and skips identical values. If another
+ * subscriber synchronously overwrites the key, later subscribers may not see the superseded
+ * value. `scheduleInitialSubscriberNotification` defers the initial cache read until relevant
+ * same-tick writes settle, without waiting for unrelated writes.
  *
  * @param connectOptions The options object that will define the behavior of the connection.
  * @param connectOptions.key The Onyx key to subscribe to.
@@ -159,48 +159,20 @@ function connect&lt;TKey extends OnyxKey&gt;(connectOptions: ConnectOptions&lt;TKey&gt;): Co
             return;
         }
&#32;
-        if (OnyxKeys.isCollectionKey(key)) {
-            // Collection-root mode: dedup skips identical collection refs. Initial fire delivers
-            // the current collection object: frozen `{}` for an empty-but-known collection,
-            // `undefined` only if the collection key has not been seen yet.
-            let lastDeliveredCollection: unknown = OnyxUtils.NOT_DELIVERED;
-            const deliverCollection = (rawCollection: OnyxValue&lt;TKey&gt; | undefined, k: TKey) =&gt; {
-                if (Object.is(lastDeliveredCollection, rawCollection)) {
-                    return;
-                }
-                lastDeliveredCollection = rawCollection;
-                (callback as CollectionConnectCallback&lt;TKey&gt; | undefined)?.(rawCollection as NonNullable&lt;OnyxCollection&lt;KeyValueMapping[TKey]&gt;&gt;, k);
-            };
-            unsubscribeFn = onyxSubscriptionManager.subscribe(key, (value, k) =&gt; {
-                deliverCollection(value as unknown as OnyxValue&lt;TKey&gt;, k as TKey);
-            });
-            PendingWrites.scheduleInitialSubscriberNotification(key, () =&gt; {
-                if (!active) {
-                    return;
-                }
-                deliverCollection(onyxSubscriptionManager.getState(key) as unknown as OnyxValue&lt;TKey&gt;, key as TKey);
-            });
-            return;
-        }
-
-        // Non-collection key (or a specific collection member): single-value subscription.
         let lastDelivered: unknown = OnyxUtils.NOT_DELIVERED;
-        const deliverValue = (value: OnyxValue&lt;TKey&gt;, k: TKey | undefined) =&gt; {
+        const deliverSnapshot = () =&gt; {
+            if (!active) {
+                return;
+            }
+            const value = onyxSubscriptionManager.getState(key) as Parameters&lt;NonNullable&lt;ConnectOptions&lt;TKey&gt;['callback']&gt;&gt;[0];
             if (Object.is(lastDelivered, value)) {
                 return;
             }
             lastDelivered = value;
-            (callback as DefaultConnectCallback&lt;TKey&gt; | undefined)?.(value, k as TKey);
+            callback?.(value, key);
         };
-        unsubscribeFn = onyxSubscriptionManager.subscribe(key, (value, k) =&gt; {
-            deliverValue(value, k as TKey);
-        });
-        PendingWrites.scheduleInitialSubscriberNotification(key, () =&gt; {
-            if (!active) {
-                return;
-            }
-            deliverValue(onyxSubscriptionManager.getState(key), key);
-        });
+        unsubscribeFn = onyxSubscriptionManager.subscribe(key, deliverSnapshot).unsubscribe;
+        PendingWrites.scheduleInitialSubscriberNotification(key, deliverSnapshot);
     };
&#32;
     OnyxUtils.afterInit(() =&gt; {
@@ -236,8 +208,10 @@ function connect&lt;TKey extends OnyxKey&gt;(connectOptions: ConnectOptions&lt;TKey&gt;): Co
  * For a collection root key, the callback fires with the entire frozen collection
  * object whenever any member changes; signature `(collection, collectionKey)`.
  * For any other key, the callback fires with the value at that key; signature
- * `(value, key)`. Initial fire is deferred via `scheduleInitialSubscriberNotification` so it reads
- * cache after any same-tick writes have applied.
+ * `(value, key)`. The callback reads the latest snapshot and skips identical values. If another
+ * subscriber synchronously overwrites the key, later subscribers may not see the superseded
+ * value. `scheduleInitialSubscriberNotification` defers the initial cache read until relevant
+ * same-tick writes settle, without waiting for unrelated writes.
  *
  * @param connectOptions The options object that will define the behavior of the connection.
  * @param connectOptions.key The Onyx key to subscribe to.
diff --git a/lib/OnyxSubscriptionManager.ts b/lib/OnyxSubscriptionManager.ts
index 8fe2833e..e4a446f8 100644
--- a/lib/OnyxSubscriptionManager.ts
+++ b/lib/OnyxSubscriptionManager.ts
@@ -5,26 +5,10 @@ import cache from './OnyxCache';
 import OnyxKeys from './OnyxKeys';
 import Storage from './storage';
&#32;
-/**
- * Listener fired when an exact key's value changes.
- */
-type Listener&lt;TKey extends OnyxKey = OnyxKey&gt; = (value: OnyxValue&lt;TKey&gt;, key: TKey) =&gt; void;
-
-/**
- * Generic listener, without specific types for the keys or values.
- * This way a single Map can hold listeners for every key type.
- */
-type GenericListener = (value: unknown, key: OnyxKey) =&gt; void;
-
-/** Listener fired when any of a state listener's dependency keys changes. Used by `useOnyxState`. */
-type StateListenerCallback = () =&gt; void;
-
-type StateListenerEntry = {
-    listener: StateListenerCallback;
-    deps: Set&lt;OnyxKey&gt;;
-};
+/** Signals that a subscriber should re-read its snapshot. */
+type Listener = () =&gt; void;
&#32;
-type StateSubscription = {
+type Subscription = {
     /** Moves the subscription to `deps`, adding and removing only the keys that differ. */
     updateDeps: (deps: readonly OnyxKey[]) =&gt; void;
     unsubscribe: () =&gt; void;
@@ -57,21 +41,10 @@ function reportCacheMissIfStorageHasValue(key: OnyxKey): void {
 }
&#32;
 /**
- * OnyxSubscriptionManager is a registry for Onyx subscriptions, backed by two indexes:
- *    - keyListeners:        exact-key listeners, keyed by OnyxKey (a single key, a collection object,
- *                           or a collection member). Notified via `notifyKey`/`notifyCollection`.
- *    - stateListenersByDep: listeners that re-evaluate when any of their dependency keys change,
- *                           indexed by dep key. Used by `useOnyxState`.
+ * Indexes snapshot listeners by dependency key. A collection key is a dependency on all its members.
  */
 class OnyxSubscriptionManager {
-    private keyListeners: Map&lt;OnyxKey, Set&lt;GenericListener&gt;&gt;;
-
-    private stateListenersByDep: Map&lt;OnyxKey, Set&lt;StateListenerEntry&gt;&gt;;
-
-    constructor() {
-        this.keyListeners = new Map();
-        this.stateListenersByDep = new Map();
-    }
+    private listenersByDep = new Map&lt;OnyxKey, Set&lt;Listener&gt;&gt;();
&#32;
     /**
      * Returns the frozen collection object for collection
@@ -90,48 +63,14 @@ class OnyxSubscriptionManager {
         return value;
     }
&#32;
-    /**
-     * Subscribe to an exact key. For a collection root key this is "collection mode": the
-     * listener fires with the frozen collection object whenever any member changes. For a
-     * collection member key or a regular key, the listener fires when that key's value changes.
-     *
-     * Returns an unsubscribe function.
-     */
-    subscribe&lt;TKey extends OnyxKey&gt;(key: TKey, listener: Listener&lt;TKey&gt;): () =&gt; void {
-        let listeners = this.keyListeners.get(key);
-        if (!listeners) {
-            listeners = new Set();
-            this.keyListeners.set(key, listeners);
-        }
-
-        listeners.add(listener as GenericListener);
-
-        return () =&gt; {
-            const set = this.keyListeners.get(key);
-            if (!set) {
-                return;
-            }
-
-            set.delete(listener as GenericListener);
-
-            if (set.size === 0) {
-                this.keyListeners.delete(key);
-            }
-        };
-    }
-
-    /**
-     * Subscribe to state-tree changes. The listener fires when any of the dependency keys changes.
-     * A collection key counts as a single dep: any member change fires it. Used by `useOnyxState`.
-     *
-     * Returns a handle. `updateDeps` moves the subscription to a new dep set, touching only the keys
-     * that were added or removed.
-     */
-    subscribeState(listener: StateListenerCallback, deps: readonly OnyxKey[]): StateSubscription {
-        const entry: StateListenerEntry = {listener, deps: new Set(deps)};
+    /** Subscribe to one or more dependencies, with one signal per dispatch. */
+    subscribe(deps: OnyxKey | readonly OnyxKey[], listener: Listener): Subscription {
+        // Give each subscription its own identity, even when callers share a callback.
+        const entry = () =&gt; listener();
+        let currentDeps: readonly OnyxKey[] | Set&lt;OnyxKey&gt; = typeof deps === 'string' ? [deps] : new Set(deps);
         let isSubscribed = true;
-        for (const dep of entry.deps) {
-            this.addStateEntry(dep, entry);
+        for (const dep of currentDeps) {
+            this.addListener(dep, entry);
         }
&#32;
         return {
@@ -139,140 +78,79 @@ class OnyxSubscriptionManager {
                 if (!isSubscribed) {
                     return;
                 }
+                const previous = currentDeps instanceof Set ? currentDeps : new Set(currentDeps);
                 const next = new Set(nextDeps);
-                for (const dep of entry.deps) {
+                for (const dep of previous) {
                     if (!next.has(dep)) {
-                        this.removeStateEntry(dep, entry);
+                        this.removeListener(dep, entry);
                     }
                 }
                 for (const dep of next) {
-                    if (!entry.deps.has(dep)) {
-                        this.addStateEntry(dep, entry);
+                    if (!previous.has(dep)) {
+                        this.addListener(dep, entry);
                     }
                 }
-                entry.deps = next;
+                currentDeps = next;
             },
             unsubscribe: () =&gt; {
                 if (!isSubscribed) {
                     return;
                 }
                 isSubscribed = false;
-                for (const dep of entry.deps) {
-                    this.removeStateEntry(dep, entry);
+                for (const dep of currentDeps) {
+                    this.removeListener(dep, entry);
                 }
             },
         };
     }
&#32;
-    /**
-     * Notify of a single-key write.
-     *
-     * Dispatch:
-     *   1. keyListeners.get(key): exact-key subscribers (always fires).
-     *   2. If key is a collection member, keyListeners.get(collectionKey): collection
-     *      listeners for the parent collection.
-     *   3. State listeners whose deps include `key` or its collection key.
-     */
-    notifyKey&lt;TKey extends OnyxKey&gt;(key: TKey, value: OnyxValue&lt;TKey&gt;): void {
-        // 1. Exact-key listeners
-        const exact = this.keyListeners.get(key);
-        if (exact &amp;&amp; exact.size &gt; 0) {
-            for (const listener of [...exact]) {
-                this.safeInvoke(() =&gt; listener(value, key), key);
-            }
-        }
-
-        // 2. Collection-level routing. Only fires when the write is to a member key.
-        // Direct writes to a collection root (e.g. `Onyx.merge(COLLECTION_KEY, ...)`) are an
-        // unsupported anti-pattern; treat them as opaque single-key writes.
-        const collectionKey = OnyxKeys.getCollectionKey(key);
-        const isCollectionMemberWrite = collectionKey !== undefined &amp;&amp; collectionKey !== key;
-        if (isCollectionMemberWrite) {
-            const collectionListeners = this.keyListeners.get(collectionKey);
-            if (collectionListeners &amp;&amp; collectionListeners.size &gt; 0) {
-                const collectionData = cache.getCollectionData(collectionKey);
-                for (const listener of [...collectionListeners]) {
-                    this.safeInvoke(() =&gt; listener(collectionData, collectionKey), collectionKey);
-                }
-            }
-        }
-
-        // 3. State listeners, fired at most once even when both the member and its collection key match.
-        if (this.stateListenersByDep.size === 0) {
+    /** Signal the key and, for a member write, its parent collection. */
+    notifyKey(key: OnyxKey): void {
+        if (this.listenersByDep.size === 0) {
             return;
         }
-        const fired = new Set&lt;StateListenerCallback&gt;();
-        this.fireStateListenersForDep(key, fired);
-        if (isCollectionMemberWrite) {
-            this.fireStateListenersForDep(collectionKey, fired);
+        const collectionKey = OnyxKeys.getCollectionKey(key);
+        const hasParentListeners = collectionKey !== undefined &amp;&amp; collectionKey !== key &amp;&amp; this.listenersByDep.has(collectionKey);
+        if (!hasParentListeners) {
+            this.dispatch(key);
+        } else if (this.listenersByDep.has(key)) {
+            this.dispatch(key, [collectionKey]);
+        } else {
+            this.dispatch(collectionKey);
         }
     }
&#32;
-    /**
-     * Notify of a collection-level batch update.
-     *
-     * Dispatch:
-     *   1. keyListeners.get(collectionKey): fires once with the new collection object.
-     *   2. keyListeners.get(memberKey): fires per changed member whose value differs from
-     *      the previous, preserving ref-equality on unchanged members.
-     *   3. State listeners affected by the collection key or any member key whose value differs from
-     *      the previous, each fired at most once.
-     */
+    /** Signal the collection and members not known to have kept their previous reference. */
     notifyCollection&lt;TKey extends CollectionKeyBase&gt;(
         collectionKey: TKey,
         partialCollection: OnyxCollection&lt;KeyValueMapping[TKey]&gt;,
         partialPreviousCollection?: OnyxCollection&lt;KeyValueMapping[TKey]&gt;,
     ): void {
+        if (this.listenersByDep.size === 0) {
+            return;
+        }
         const changedKeys = Object.keys(partialCollection ?? {});
         if (changedKeys.length === 0) {
             return;
         }
-        // Read the merged collection once. `cache.getCollectionData()` returns the post-merge
-        // frozen object, which is what listeners should see (not the raw `partialCollection`
-        // input, which is just the delta and lacks fields preserved during merge).
-        const collectionData = cache.getCollectionData(collectionKey);
-
-        // 1. Collection listeners fire once with the new collection object.
-        const collectionListeners = this.keyListeners.get(collectionKey);
-        if (collectionListeners &amp;&amp; collectionListeners.size &gt; 0) {
-            for (const listener of [...collectionListeners]) {
-                this.safeInvoke(() =&gt; listener(collectionData, collectionKey), collectionKey);
-            }
-        }
-
-        // 2. Exact-member subscribers fire per changed key (skip if ref unchanged vs previous).
-        // Only treat a member as unchanged when `previous` actually carries it: when the
-        // previous collection is omitted, a removed member reads `undefined` on both sides
-        // and would otherwise be skipped even though it changed.
-        const hasStateListeners = this.stateListenersByDep.size &gt; 0;
-        const changedMemberKeys: string[] | null = hasStateListeners ? [] : null;
+        let firstDep: OnyxKey | undefined = this.listenersByDep.has(collectionKey) ? collectionKey : undefined;
+        let otherDeps: OnyxKey[] | undefined;
         for (const memberKey of changedKeys) {
-            const value = collectionData?.[memberKey];
-            const prev = partialPreviousCollection?.[memberKey];
-            if (partialPreviousCollection &amp;&amp; Object.prototype.hasOwnProperty.call(partialPreviousCollection, memberKey) &amp;&amp; value === prev) {
+            if (memberKey === collectionKey || !this.listenersByDep.has(memberKey)) {
                 continue;
             }
-            changedMemberKeys?.push(memberKey);
-
-            const exact = this.keyListeners.get(memberKey);
-            if (!exact || exact.size === 0) {
+            // Without a previous entry, undefined may mean a removal rather than a no-op.
+            if (partialPreviousCollection &amp;&amp; Object.prototype.hasOwnProperty.call(partialPreviousCollection, memberKey) &amp;&amp; cache.get(memberKey) === partialPreviousCollection[memberKey]) {
                 continue;
             }
-
-            for (const listener of [...exact]) {
-                this.safeInvoke(() =&gt; listener(value, memberKey), memberKey);
+            if (firstDep === undefined) {
+                firstDep = memberKey;
+            } else {
+                (otherDeps ??= []).push(memberKey);
             }
         }
-
-        // 3. State listeners, each fired at most once across the collection and its members. Members
-        // that step 2 found unchanged are skipped here too.
-        if (changedMemberKeys === null) {
-            return;
-        }
-        const fired = new Set&lt;StateListenerCallback&gt;();
-        this.fireStateListenersForDep(collectionKey, fired);
-        for (const memberKey of changedMemberKeys) {
-            this.fireStateListenersForDep(memberKey, fired);
+        if (firstDep !== undefined) {
+            this.dispatch(firstDep, otherDeps);
         }
     }
&#32;
@@ -280,8 +158,7 @@ class OnyxSubscriptionManager {
      * Wipe all subscriptions. Used by tests and `Onyx.clear()` follow-on.
      */
     clearAll(): void {
-        this.keyListeners.clear();
-        this.stateListenersByDep.clear();
+        this.listenersByDep.clear();
         this.resetCacheMissReports();
     }
&#32;
@@ -293,58 +170,58 @@ class OnyxSubscriptionManager {
      * True if there are any subscribers for the given key (exact or parent collection).
      */
     hasListenersForKey(key: OnyxKey): boolean {
-        if (this.hasListenersForExactKey(key)) {
+        if (this.listenersByDep.has(key)) {
             return true;
         }
&#32;
         const collectionKey = OnyxKeys.getCollectionKey(key);
-        return collectionKey !== undefined &amp;&amp; collectionKey !== key &amp;&amp; this.hasListenersForExactKey(collectionKey);
-    }
-
-    /**
-     * True if `key` itself has a key listener or a state listener. The parent collection is not checked.
-     */
-    private hasListenersForExactKey(key: OnyxKey): boolean {
-        return (this.keyListeners.get(key)?.size ?? 0) &gt; 0 || (this.stateListenersByDep.get(key)?.size ?? 0) &gt; 0;
+        return collectionKey !== undefined &amp;&amp; collectionKey !== key &amp;&amp; this.listenersByDep.has(collectionKey);
     }
&#32;
-    private addStateEntry(dep: OnyxKey, entry: StateListenerEntry): void {
-        let set = this.stateListenersByDep.get(dep);
+    private addListener(dep: OnyxKey, listener: Listener): void {
+        let set = this.listenersByDep.get(dep);
         if (!set) {
             set = new Set();
-            this.stateListenersByDep.set(dep, set);
+            this.listenersByDep.set(dep, set);
         }
-        set.add(entry);
+        set.add(listener);
     }
&#32;
-    private removeStateEntry(dep: OnyxKey, entry: StateListenerEntry): void {
-        const set = this.stateListenersByDep.get(dep);
-        if (!set) {
+    private removeListener(dep: OnyxKey, listener: Listener): void {
+        const set = this.listenersByDep.get(dep);
+        if (!set?.delete(listener)) {
             return;
         }
-        set.delete(entry);
         if (set.size === 0) {
-            this.stateListenersByDep.delete(dep);
+            this.listenersByDep.delete(dep);
         }
     }
&#32;
-    /**
-     * Fires each state listener registered on `depKey`, skipping any already fired this dispatch.
-     * Tracked by callback rather than by entry: a listener that re-subscribes while it runs gets a
-     * new entry, which a later dep of the same dispatch would otherwise fire again.
-     */
-    private fireStateListenersForDep(depKey: OnyxKey, alreadyFired: Set&lt;StateListenerCallback&gt;): void {
-        const set = this.stateListenersByDep.get(depKey);
-        if (!set || set.size === 0) {
+    private dispatch(firstDep: OnyxKey, otherDeps?: readonly OnyxKey[]): void {
+        // A single bucket is already deduplicated by its Set.
+        if (!otherDeps) {
+            this.fireListeners(firstDep);
+            return;
+        }
+        const fired = new Set&lt;Listener&gt;();
+        this.fireListeners(firstDep, fired);
+        for (const dep of otherDeps) {
+            this.fireListeners(dep, fired);
+        }
+    }
+
+    private fireListeners(dep: OnyxKey, fired?: Set&lt;Listener&gt;): void {
+        const listeners = this.listenersByDep.get(dep);
+        if (!listeners) {
             return;
         }
&#32;
-        for (const entry of [...set]) {
-            if (alreadyFired.has(entry.listener)) {
+        for (const listener of [...listeners]) {
+            if (fired?.has(listener)) {
                 continue;
             }
-            alreadyFired.add(entry.listener);
-            this.safeInvoke(entry.listener, depKey);
+            fired?.add(listener);
+            this.safeInvoke(listener, dep);
         }
     }
&#32;
@@ -363,4 +240,4 @@ class OnyxSubscriptionManager {
 const onyxSubscriptionManager = new OnyxSubscriptionManager();
&#32;
 export default onyxSubscriptionManager;
-export type {Listener, StateSubscription};
+export type {Subscription};
diff --git a/lib/OnyxUtils.ts b/lib/OnyxUtils.ts
index 04070f83..c49f58bb 100644
--- a/lib/OnyxUtils.ts
+++ b/lib/OnyxUtils.ts
@@ -517,7 +517,7 @@ function notifyKey&lt;TKey extends OnyxKey&gt;(key: TKey, value: OnyxValue&lt;TKey&gt;): voi
     } else {
         cache.removeLastAccessedKey(key);
     }
-    onyxSubscriptionManager.notifyKey(key, value);
+    onyxSubscriptionManager.notifyKey(key);
 }
&#32;
 /**
diff --git a/lib/useOnyx.ts b/lib/useOnyx.ts
index 4c1d826d..e270b2d8 100644
--- a/lib/useOnyx.ts
+++ b/lib/useOnyx.ts
@@ -70,7 +70,7 @@ function useOnyx&lt;TKey extends OnyxKey, TReturnValue = OnyxValue&lt;TKey&gt;&gt;(key: TKey
&#32;
     const subscribe = useCallback(
         (onStoreChange: () =&gt; void) =&gt; {
-            const unsubscribe = onyxSubscriptionManager.subscribe(key, onStoreChange);
+            const {unsubscribe} = onyxSubscriptionManager.subscribe(key, onStoreChange);
&#32;
             // `Onyx.init` hydrates the cache without notifying anyone, so a subscriber that mounted
             // before it finished would never hear about the stored value. Re-read once init lands.
diff --git a/lib/useOnyxState.ts b/lib/useOnyxState.ts
index 1a9560be..70cf9eef 100644
--- a/lib/useOnyxState.ts
+++ b/lib/useOnyxState.ts
@@ -188,7 +188,7 @@ function useOnyxState&lt;TReturnValue&gt;(selector: UseOnyxStateSelector&lt;TReturnValue&gt;
         let isActive = true;
         // React subscribes after the commit, so the snapshot behind the committed value is already there.
         let keys = committedSnapshotterRef.current?.peek()?.deps ?? [];
-        const subscription = onyxSubscriptionManager.subscribeState(handleStoreChange, keys);
+        const subscription = onyxSubscriptionManager.subscribe(keys, handleStoreChange);
&#32;
         /** Moves the subscription to the keys the latest selector run read. */
         function syncKeys() {
diff --git a/tests/perf-test/OnyxSubscriptionManager.perf-test.ts b/tests/perf-test/OnyxSubscriptionManager.perf-test.ts
index b1df9f71..9c0dbd7f 100644
--- a/tests/perf-test/OnyxSubscriptionManager.perf-test.ts
+++ b/tests/perf-test/OnyxSubscriptionManager.perf-test.ts
@@ -35,7 +35,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
             await measureFunction(
                 () =&gt; {
-                    unsubscribe = onyxSubscriptionManager.subscribe(`${collectionKey}0`, jest.fn());
+                    unsubscribe = onyxSubscriptionManager.subscribe(`${collectionKey}0`, jest.fn()).unsubscribe;
                 },
                 {
                     beforeEach: async () =&gt; {
@@ -54,7 +54,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
             await measureFunction(
                 () =&gt; {
-                    unsubscribe = onyxSubscriptionManager.subscribe(collectionKey, jest.fn());
+                    unsubscribe = onyxSubscriptionManager.subscribe(collectionKey, jest.fn()).unsubscribe;
                 },
                 {
                     beforeEach: async () =&gt; {
@@ -76,7 +76,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
             await measureFunction(() =&gt; unsubscribe?.(), {
                 beforeEach: async () =&gt; {
-                    unsubscribe = onyxSubscriptionManager.subscribe(key, jest.fn());
+                    unsubscribe = onyxSubscriptionManager.subscribe(key, jest.fn()).unsubscribe;
                 },
                 afterEach: clearOnyxAfterEachMeasure,
             });
diff --git a/tests/perf-test/OnyxUtils.perf-test.ts b/tests/perf-test/OnyxUtils.perf-test.ts
index b428c6c5..a30c6149 100644
--- a/tests/perf-test/OnyxUtils.perf-test.ts
+++ b/tests/perf-test/OnyxUtils.perf-test.ts
@@ -283,7 +283,7 @@ describe('OnyxUtils', () =&gt; {
                 beforeEach: async () =&gt; {
                     await Onyx.multiSet(mockedReportActionsMap);
                     for (const key of mockedReportActionsKeys) {
-                        unsubscribes.push(onyxSubscriptionManager.subscribe(key, jest.fn()));
+                        unsubscribes.push(onyxSubscriptionManager.subscribe(key, jest.fn()).unsubscribe);
                     }
                 },
                 afterEach: async () =&gt; {
@@ -309,7 +309,7 @@ describe('OnyxUtils', () =&gt; {
                 beforeEach: async () =&gt; {
                     await Onyx.set(key, previousReportAction);
                     for (let i = 0; i &lt; 10000; i++) {
-                        unsubscribes.push(onyxSubscriptionManager.subscribe(key, jest.fn()));
+                        unsubscribes.push(onyxSubscriptionManager.subscribe(key, jest.fn()).unsubscribe);
                     }
                 },
                 afterEach: async () =&gt; {
diff --git a/tests/unit/OnyxSubscriptionManagerTest.ts b/tests/unit/OnyxSubscriptionManagerTest.ts
index c10b4249..910ee9f1 100644
--- a/tests/unit/OnyxSubscriptionManagerTest.ts
+++ b/tests/unit/OnyxSubscriptionManagerTest.ts
@@ -1,7 +1,7 @@
 import type {OnyxKey} from '../../lib';
 import Onyx from '../../lib';
 import onyxSubscriptionManager from '../../lib/OnyxSubscriptionManager';
-import type {StateSubscription} from '../../lib/OnyxSubscriptionManager';
+import type {Subscription} from '../../lib/OnyxSubscriptionManager';
 import cache from '../../lib/OnyxCache';
 import * as Logger from '../../lib/Logger';
 import OnyxKeys from '../../lib/OnyxKeys';
@@ -10,10 +10,8 @@ import createDeferredTask from '../../lib/createDeferredTask';
 import waitForPromisesToResolve from '../utils/waitForPromisesToResolve';
&#32;
 // We need access to some internal properties of `onyxSubscriptionManager` during the tests but they are private,
-// so this workaround allows us to have access to them. The maps are created once in the constructor
-// and only ever `.clear()`ed (never reassigned), so capturing the references here stays valid.
-const keyListeners = onyxSubscriptionManager['keyListeners'];
-const stateListenersByDep = onyxSubscriptionManager['stateListenersByDep'];
+// so this workaround allows us to inspect the dependency index.
+const listenersByDep = onyxSubscriptionManager['listenersByDep'];
&#32;
 const ONYXKEYS = {
     TEST_KEY: 'test',
@@ -45,14 +43,14 @@ describe('OnyxSubscriptionManager', () =&gt; {
     });
&#32;
     describe('subscribe / notifyKey', () =&gt; {
-        it('should fire the listener with (value, key) on notifyKey', () =&gt; {
+        it('should signal listeners without a write payload', () =&gt; {
             const callback = jest.fn();
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'hello');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
-            expect(callback).toHaveBeenCalledWith('hello', ONYXKEYS.TEST_KEY);
+            expect(callback).toHaveBeenCalledWith();
         });
&#32;
         it('should fire all listeners registered on the same key', () =&gt; {
@@ -61,7 +59,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback1);
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback2);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 1);
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(callback1).toHaveBeenCalledTimes(1);
             expect(callback2).toHaveBeenCalledTimes(1);
@@ -69,50 +67,49 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
         it('should not fire the listener after it unsubscribes', () =&gt; {
             const callback = jest.fn();
-            const unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
+            const {unsubscribe} = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'first');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             unsubscribe();
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'second');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
-            expect(callback).toHaveBeenLastCalledWith('first', ONYXKEYS.TEST_KEY);
         });
&#32;
         it('should only unsubscribe the specific listener, leaving others intact', () =&gt; {
             const callback1 = jest.fn();
             const callback2 = jest.fn();
-            const unsubscribe1 = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback1);
+            const {unsubscribe: unsubscribe1} = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback1);
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback2);
&#32;
             unsubscribe1();
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 1);
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(callback1).not.toHaveBeenCalled();
             expect(callback2).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should delete the key entry from the internal map once the last listener unsubscribes', () =&gt; {
-            const unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, jest.fn());
-            expect(keyListeners.has(ONYXKEYS.TEST_KEY)).toBeTruthy();
+            const {unsubscribe} = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, jest.fn());
+            expect(listenersByDep.has(ONYXKEYS.TEST_KEY)).toBeTruthy();
&#32;
             unsubscribe();
&#32;
-            expect(keyListeners.has(ONYXKEYS.TEST_KEY)).toBeFalsy();
+            expect(listenersByDep.has(ONYXKEYS.TEST_KEY)).toBeFalsy();
         });
&#32;
         it('should be a no-op to notify a key with no listeners', () =&gt; {
-            expect(() =&gt; onyxSubscriptionManager.notifyKey('keyWithNoListeners' as OnyxKey, 'x')).not.toThrow();
+            expect(() =&gt; onyxSubscriptionManager.notifyKey('keyWithNoListeners' as OnyxKey)).not.toThrow();
         });
&#32;
         it('should be idempotent when unsubscribing more than once', () =&gt; {
             const callback = jest.fn();
-            const unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
+            const {unsubscribe} = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
&#32;
             unsubscribe();
             expect(() =&gt; unsubscribe()).not.toThrow();
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 1);
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             expect(callback).not.toHaveBeenCalled();
         });
     });
@@ -141,65 +138,56 @@ describe('OnyxSubscriptionManager', () =&gt; {
     });
&#32;
     describe('collection routing on notifyKey', () =&gt; {
-        it('should fire the collection-root listener with the cache collection object when a member is written', () =&gt; {
-            const collectionData = {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}};
-            const getCollectionData = jest.spyOn(cache, 'getCollectionData').mockReturnValue(collectionData);
-
+        it('should signal the collection root without reading its snapshot', () =&gt; {
+            const getCollectionData = jest.spyOn(cache, 'getCollectionData');
             const callback = jest.fn();
             onyxSubscriptionManager.subscribe(COLLECTION, callback);
&#32;
-            onyxSubscriptionManager.notifyKey(MEMBER_1, {id: 1});
+            onyxSubscriptionManager.notifyKey(MEMBER_1);
&#32;
-            expect(getCollectionData).toHaveBeenCalledWith(COLLECTION);
             expect(callback).toHaveBeenCalledTimes(1);
-            expect(callback).toHaveBeenCalledWith(collectionData, COLLECTION);
+            expect(getCollectionData).not.toHaveBeenCalled();
         });
&#32;
         it('should fire both the exact-member listener and the collection-root listener', () =&gt; {
-            const collectionData = {[MEMBER_1]: {id: 1}};
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue(collectionData);
-
             const memberCallback = jest.fn();
             const collectionCallback = jest.fn();
             onyxSubscriptionManager.subscribe(MEMBER_1, memberCallback);
             onyxSubscriptionManager.subscribe(COLLECTION, collectionCallback);
&#32;
-            onyxSubscriptionManager.notifyKey(MEMBER_1, {id: 1});
+            onyxSubscriptionManager.notifyKey(MEMBER_1);
&#32;
-            expect(memberCallback).toHaveBeenCalledWith({id: 1}, MEMBER_1);
-            expect(collectionCallback).toHaveBeenCalledWith(collectionData, COLLECTION);
+            expect(memberCallback).toHaveBeenCalledTimes(1);
+            expect(collectionCallback).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should not perform collection routing for a non-member single key', () =&gt; {
-            const getCollectionData = jest.spyOn(cache, 'getCollectionData');
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
+            onyxSubscriptionManager.subscribe(COLLECTION, callback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
-            expect(callback).toHaveBeenCalledTimes(1);
-            expect(getCollectionData).not.toHaveBeenCalled();
+            expect(callback).not.toHaveBeenCalled();
         });
     });
&#32;
     describe('notifyCollection', () =&gt; {
-        it('should fire the collection listener once with the cache collection object', () =&gt; {
-            const collectionData = {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}};
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue(collectionData);
-
+        it('should signal the collection once without building a snapshot', () =&gt; {
+            const getCollectionData = jest.spyOn(cache, 'getCollectionData');
             const callback = jest.fn();
             onyxSubscriptionManager.subscribe(COLLECTION, callback);
&#32;
             onyxSubscriptionManager.notifyCollection(COLLECTION, {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}});
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
-            expect(callback).toHaveBeenCalledWith(collectionData, COLLECTION);
+            expect(getCollectionData).not.toHaveBeenCalled();
         });
&#32;
         it('should fire exact-member listeners only for members whose value reference changed', () =&gt; {
             const shared = {id: 2}; // same reference in collection and previous, should be skipped
-            const collectionData = {[MEMBER_1]: {id: 1}, [MEMBER_2]: shared};
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue(collectionData);
+            cache.set(MEMBER_1, {id: 1});
+            cache.set(MEMBER_2, shared);
+            const getCollectionData = jest.spyOn(cache, 'getCollectionData');
&#32;
             const member1Callback = jest.fn();
             const member2Callback = jest.fn();
@@ -212,14 +200,12 @@ describe('OnyxSubscriptionManager', () =&gt; {
                 {[MEMBER_2]: shared}, // previous: member 2 unchanged by reference
             );
&#32;
-            expect(member1Callback).toHaveBeenCalledWith({id: 1}, MEMBER_1);
+            expect(member1Callback).toHaveBeenCalledTimes(1);
             expect(member2Callback).not.toHaveBeenCalled();
+            expect(getCollectionData).not.toHaveBeenCalled();
         });
&#32;
         it('should notify the exact-member listener when the member is deleted without a previous collection', () =&gt; {
-            // member1 has already been removed from the cache by the time notifyCollection runs.
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue({[MEMBER_2]: {id: 2}});
-
             const member1Callback = jest.fn();
             onyxSubscriptionManager.subscribe(MEMBER_1, member1Callback);
&#32;
@@ -240,52 +226,50 @@ describe('OnyxSubscriptionManager', () =&gt; {
         });
     });
&#32;
-    describe('subscribeState', () =&gt; {
+    describe('dependency sets', () =&gt; {
         it('should fire a state listener when one of its deps changes', () =&gt; {
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribeState(callback, [ONYXKEYS.TEST_KEY]);
+            onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], callback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should not fire when a non-dependency key changes', () =&gt; {
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribeState(callback, [ONYXKEYS.TEST_KEY]);
+            onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], callback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.OTHER_TEST, 'x');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.OTHER_TEST);
&#32;
             expect(callback).not.toHaveBeenCalled();
         });
&#32;
         it('should fire a listener that depends on a collection key when a member is written', () =&gt; {
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribeState(callback, [COLLECTION]);
+            onyxSubscriptionManager.subscribe([COLLECTION], callback);
&#32;
-            onyxSubscriptionManager.notifyKey(MEMBER_1, {id: 1});
+            onyxSubscriptionManager.notifyKey(MEMBER_1);
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should fire only once when a listener depends on both a member and its collection key', () =&gt; {
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribeState(callback, [MEMBER_1, COLLECTION]);
+            onyxSubscriptionManager.subscribe([MEMBER_1, COLLECTION], callback);
&#32;
-            onyxSubscriptionManager.notifyKey(MEMBER_1, {id: 1});
+            onyxSubscriptionManager.notifyKey(MEMBER_1);
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should fire collection and member state listeners once each on notifyCollection', () =&gt; {
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue({[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}});
-
             const collectionCallback = jest.fn();
             const member1Callback = jest.fn();
             const bothCallback = jest.fn();
-            onyxSubscriptionManager.subscribeState(collectionCallback, [COLLECTION]);
-            onyxSubscriptionManager.subscribeState(member1Callback, [MEMBER_1]);
-            onyxSubscriptionManager.subscribeState(bothCallback, [COLLECTION, MEMBER_1]);
+            onyxSubscriptionManager.subscribe([COLLECTION], collectionCallback);
+            onyxSubscriptionManager.subscribe([MEMBER_1], member1Callback);
+            onyxSubscriptionManager.subscribe([COLLECTION, MEMBER_1], bothCallback);
&#32;
             onyxSubscriptionManager.notifyCollection(COLLECTION, {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}});
&#32;
@@ -298,11 +282,12 @@ describe('OnyxSubscriptionManager', () =&gt; {
             // Given a batch that re-sends one member with the reference it already had and changes another
             const unchangedMember = {id: 1};
             const changedMember = {id: 2};
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue({[MEMBER_1]: unchangedMember, [MEMBER_2]: changedMember});
+            cache.set(MEMBER_1, unchangedMember);
+            cache.set(MEMBER_2, changedMember);
             const unchangedCallback = jest.fn();
             const changedCallback = jest.fn();
-            onyxSubscriptionManager.subscribeState(unchangedCallback, [MEMBER_1]);
-            onyxSubscriptionManager.subscribeState(changedCallback, [MEMBER_2]);
+            onyxSubscriptionManager.subscribe([MEMBER_1], unchangedCallback);
+            onyxSubscriptionManager.subscribe([MEMBER_2], changedCallback);
&#32;
             // When the batch is dispatched with the previous values
             onyxSubscriptionManager.notifyCollection(COLLECTION, {[MEMBER_1]: unchangedMember, [MEMBER_2]: changedMember}, {[MEMBER_1]: unchangedMember, [MEMBER_2]: {id: 0}});
@@ -315,9 +300,9 @@ describe('OnyxSubscriptionManager', () =&gt; {
         it('should fire a member state listener on notifyCollection when the previous collection does not carry that member', () =&gt; {
             // Given a batch whose previous collection says nothing about the member, so it cannot be proven unchanged
             const member = {id: 1};
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue({[MEMBER_1]: member});
+            cache.set(MEMBER_1, member);
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribeState(callback, [MEMBER_1]);
+            onyxSubscriptionManager.subscribe([MEMBER_1], callback);
&#32;
             // When the batch is dispatched
             onyxSubscriptionManager.notifyCollection(COLLECTION, {[MEMBER_1]: member}, {});
@@ -328,27 +313,28 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
         it('should fire a listener only once when it re-subscribes with more deps during the dispatch', () =&gt; {
             // Given a listener on a member that, once fired, moves its subscription to the member and its collection
-            let subscription: StateSubscription | undefined;
+            let subscription: Subscription | undefined;
             const callback = jest.fn(() =&gt; {
                 subscription?.updateDeps([MEMBER_1, COLLECTION]);
             });
-            subscription = onyxSubscriptionManager.subscribeState(callback, [MEMBER_1]);
+            subscription = onyxSubscriptionManager.subscribe(MEMBER_1, callback);
+            onyxSubscriptionManager.subscribe(COLLECTION, jest.fn());
&#32;
             // When the member changes, which dispatches to the member dep and then to the collection dep
-            onyxSubscriptionManager.notifyKey(MEMBER_1, {id: 1});
+            onyxSubscriptionManager.notifyKey(MEMBER_1);
&#32;
-            // Then the listener fired once, because the new subscription belongs to a listener this dispatch already reached
+            // The collection bucket also sees the subscription, but it has already been signaled.
             expect(callback).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should fire a listener only once when it re-subscribes to another changed member during notifyCollection', () =&gt; {
             // Given a listener on one member that, once fired, moves its subscription to both changed members
-            jest.spyOn(cache, 'getCollectionData').mockReturnValue({[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}});
-            let subscription: StateSubscription | undefined;
+            let subscription: Subscription | undefined;
             const callback = jest.fn(() =&gt; {
                 subscription?.updateDeps([MEMBER_1, MEMBER_2]);
             });
-            subscription = onyxSubscriptionManager.subscribeState(callback, [MEMBER_1]);
+            subscription = onyxSubscriptionManager.subscribe([MEMBER_1], callback);
+            onyxSubscriptionManager.subscribe(MEMBER_2, jest.fn());
&#32;
             // When a batch changes both members
             onyxSubscriptionManager.notifyCollection(COLLECTION, {[MEMBER_1]: {id: 1}, [MEMBER_2]: {id: 2}});
@@ -359,57 +345,57 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
         it('should fire on a change to any of several deps', () =&gt; {
             const callback = jest.fn();
-            onyxSubscriptionManager.subscribeState(callback, [ONYXKEYS.TEST_KEY, ONYXKEYS.OTHER_TEST]);
+            onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY, ONYXKEYS.OTHER_TEST], callback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'a');
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.OTHER_TEST, 'b');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.OTHER_TEST);
&#32;
             expect(callback).toHaveBeenCalledTimes(2);
         });
&#32;
         it('should stop firing after unsubscribe and clean up the dep index', () =&gt; {
             const callback = jest.fn();
-            const subscription = onyxSubscriptionManager.subscribeState(callback, [ONYXKEYS.TEST_KEY]);
-            expect(stateListenersByDep.has(ONYXKEYS.TEST_KEY)).toBeTruthy();
+            const subscription = onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], callback);
+            expect(listenersByDep.has(ONYXKEYS.TEST_KEY)).toBeTruthy();
&#32;
             subscription.unsubscribe();
-            expect(stateListenersByDep.has(ONYXKEYS.TEST_KEY)).toBeFalsy();
+            expect(listenersByDep.has(ONYXKEYS.TEST_KEY)).toBeFalsy();
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             expect(callback).not.toHaveBeenCalled();
         });
&#32;
         it('should touch only the added and removed keys when updateDeps moves the subscription', () =&gt; {
             // Given a listener on two keys
             const callback = jest.fn();
-            const subscription = onyxSubscriptionManager.subscribeState(callback, [ONYXKEYS.TEST_KEY, MEMBER_1]);
-            const keptSet = stateListenersByDep.get(ONYXKEYS.TEST_KEY);
+            const subscription = onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY, MEMBER_1], callback);
+            const keptSet = listenersByDep.get(ONYXKEYS.TEST_KEY);
&#32;
             // When it drops one key and adds another
             subscription.updateDeps([ONYXKEYS.TEST_KEY, MEMBER_2]);
&#32;
             // Then the kept key's index is left alone, the dropped key is cleaned up, and the new key is indexed
-            expect(stateListenersByDep.get(ONYXKEYS.TEST_KEY)).toBe(keptSet);
-            expect(stateListenersByDep.has(MEMBER_1)).toBeFalsy();
-            expect(stateListenersByDep.has(MEMBER_2)).toBeTruthy();
+            expect(listenersByDep.get(ONYXKEYS.TEST_KEY)).toBe(keptSet);
+            expect(listenersByDep.has(MEMBER_1)).toBeFalsy();
+            expect(listenersByDep.has(MEMBER_2)).toBeTruthy();
&#32;
             // And only the current deps fire it
-            onyxSubscriptionManager.notifyKey(MEMBER_1, {id: 1});
+            onyxSubscriptionManager.notifyKey(MEMBER_1);
             expect(callback).not.toHaveBeenCalled();
-            onyxSubscriptionManager.notifyKey(MEMBER_2, {id: 2});
+            onyxSubscriptionManager.notifyKey(MEMBER_2);
             expect(callback).toHaveBeenCalledTimes(1);
         });
&#32;
         it('should ignore updateDeps after unsubscribe', () =&gt; {
             // Given a listener that has unsubscribed
-            const subscription = onyxSubscriptionManager.subscribeState(jest.fn(), [ONYXKEYS.TEST_KEY]);
+            const subscription = onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], jest.fn());
             subscription.unsubscribe();
&#32;
             // When it is asked to move to a new key
             subscription.updateDeps([MEMBER_1]);
&#32;
             // Then nothing is indexed, because a late call must not resurrect the subscription
-            expect(stateListenersByDep.has(MEMBER_1)).toBeFalsy();
+            expect(listenersByDep.has(MEMBER_1)).toBeFalsy();
         });
&#32;
         it('should isolate a throwing state listener and still fire the others', () =&gt; {
@@ -420,10 +406,10 @@ describe('OnyxSubscriptionManager', () =&gt; {
                 throw new Error('boom');
             });
             const healthyCallback = jest.fn();
-            onyxSubscriptionManager.subscribeState(throwingCallback, [ONYXKEYS.TEST_KEY]);
-            onyxSubscriptionManager.subscribeState(healthyCallback, [ONYXKEYS.TEST_KEY]);
+            onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], throwingCallback);
+            onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], healthyCallback);
&#32;
-            expect(() =&gt; onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x')).not.toThrow();
+            expect(() =&gt; onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY)).not.toThrow();
&#32;
             expect(throwingCallback).toHaveBeenCalledTimes(1);
             expect(healthyCallback).toHaveBeenCalledTimes(1);
@@ -431,6 +417,22 @@ describe('OnyxSubscriptionManager', () =&gt; {
         });
     });
&#32;
+    describe('shared callbacks', () =&gt; {
+        it('should keep one subscription active when another with the same callback unsubscribes', () =&gt; {
+            const listener = jest.fn();
+            const {unsubscribe} = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, listener);
+            const subscription = onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], listener);
+
+            unsubscribe();
+            expect(onyxSubscriptionManager.hasListenersForKey(ONYXKEYS.TEST_KEY)).toBeTruthy();
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
+            expect(listener).toHaveBeenCalledTimes(1);
+
+            subscription.unsubscribe();
+            expect(onyxSubscriptionManager.hasListenersForKey(ONYXKEYS.TEST_KEY)).toBeFalsy();
+        });
+    });
+
     describe('hasListenersForKey', () =&gt; {
         it('should return true for an exact-key subscriber', () =&gt; {
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, jest.fn());
@@ -447,14 +449,14 @@ describe('OnyxSubscriptionManager', () =&gt; {
         });
&#32;
         it('should return false after the last listener unsubscribes', () =&gt; {
-            const unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, jest.fn());
+            const {unsubscribe} = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, jest.fn());
             unsubscribe();
             expect(onyxSubscriptionManager.hasListenersForKey(ONYXKEYS.TEST_KEY)).toBeFalsy();
         });
&#32;
         it('should return true for a key a state listener depends on', () =&gt; {
             // Given a state listener, which is what `useOnyxState` registers, and no exact-key subscriber
-            onyxSubscriptionManager.subscribeState(jest.fn(), [ONYXKEYS.TEST_KEY]);
+            onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], jest.fn());
&#32;
             // Then the key counts as listened to, because a write to it fires that listener
             expect(onyxSubscriptionManager.hasListenersForKey(ONYXKEYS.TEST_KEY)).toBeTruthy();
@@ -462,7 +464,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
         it('should return true for a member key when a state listener depends on its collection', () =&gt; {
             // Given a state listener on the collection root only
-            onyxSubscriptionManager.subscribeState(jest.fn(), [COLLECTION]);
+            onyxSubscriptionManager.subscribe([COLLECTION], jest.fn());
&#32;
             // Then a member counts as listened to, because a member write fires collection deps
             expect(onyxSubscriptionManager.hasListenersForKey(MEMBER_1)).toBeTruthy();
@@ -470,7 +472,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
&#32;
         it('should return false after the last state listener unsubscribes', () =&gt; {
             // Given a state listener that has been removed
-            const subscription = onyxSubscriptionManager.subscribeState(jest.fn(), [ONYXKEYS.TEST_KEY]);
+            const subscription = onyxSubscriptionManager.subscribe([ONYXKEYS.TEST_KEY], jest.fn());
             subscription.unsubscribe();
&#32;
             // Then nothing listens to the key any more
@@ -484,7 +486,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, keyCallback);
&#32;
             onyxSubscriptionManager.clearAll();
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(keyCallback).not.toHaveBeenCalled();
             expect(onyxSubscriptionManager.hasListenersForKey(ONYXKEYS.TEST_KEY)).toBeFalsy();
@@ -496,11 +498,11 @@ describe('OnyxSubscriptionManager', () =&gt; {
             let unsubscribe: () =&gt; void = jest.fn();
             const callback = jest.fn(() =&gt; {
                 unsubscribe();
-                unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
+                unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback).unsubscribe;
             });
-            unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback);
+            unsubscribe = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, callback).unsubscribe;
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
&#32;
             expect(callback).toHaveBeenCalledTimes(1);
         });
@@ -512,13 +514,12 @@ describe('OnyxSubscriptionManager', () =&gt; {
             });
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, firstCallback);
&#32;
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'first');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             expect(lateCallback).not.toHaveBeenCalled();
&#32;
             // It receives later notifications normally.
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'second');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             expect(lateCallback).toHaveBeenCalledTimes(1);
-            expect(lateCallback).toHaveBeenCalledWith('second', ONYXKEYS.TEST_KEY);
         });
&#32;
         it('should still fire a sibling unsubscribed during dispatch this round, but not on later notifications', () =&gt; {
@@ -528,14 +529,14 @@ describe('OnyxSubscriptionManager', () =&gt; {
                 unsubscribeSibling();
             });
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, firstCallback);
-            unsubscribeSibling = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, siblingCallback);
+            unsubscribeSibling = onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, siblingCallback).unsubscribe;
&#32;
             // The sibling was registered when dispatch began, so the snapshot still fires it.
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'first');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             expect(siblingCallback).toHaveBeenCalledTimes(1);
&#32;
             // Now unsubscribed, it does not fire again.
-            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'second');
+            onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY);
             expect(siblingCallback).toHaveBeenCalledTimes(1);
         });
     });
@@ -552,7 +553,7 @@ describe('OnyxSubscriptionManager', () =&gt; {
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, throwingCallback);
             onyxSubscriptionManager.subscribe(ONYXKEYS.TEST_KEY, healthyCallback);
&#32;
-            expect(() =&gt; onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY, 'x')).not.toThrow();
+            expect(() =&gt; onyxSubscriptionManager.notifyKey(ONYXKEYS.TEST_KEY)).not.toThrow();
&#32;
             expect(throwingCallback).toHaveBeenCalledTimes(1);
             expect(healthyCallback).toHaveBeenCalledTimes(1);
diff --git a/tests/unit/onyxTest.ts b/tests/unit/onyxTest.ts
index 8ccefb6e..2543722e 100644
--- a/tests/unit/onyxTest.ts
+++ b/tests/unit/onyxTest.ts
@@ -158,6 +158,37 @@ describe('Onyx', () =&gt; {
         }
     });
&#32;
+    it('should not deliver a superseded snapshot when another subscriber synchronously writes to the same key', async () =&gt; {
+        const key = ONYX_KEYS.RAM_ONLY_TEST_KEY;
+        const initial = {phase: 'initial'};
+        const inner = {phase: 'inner'};
+        await Onyx.set(key, initial);
+        let innerWrite: Promise&lt;void&gt; | undefined;
+        const writer = Onyx.connectWithoutView({
+            key,
+            callback: (value) =&gt; {
+                if (value?.phase === 'outer') {
+                    innerWrite = Onyx.set(key, inner);
+                }
+            },
+        });
+        const callback = jest.fn();
+        connection = Onyx.connectWithoutView({key, callback});
+
+        try {
+            await waitForPromisesToResolve();
+            expect(callback).toHaveBeenCalledWith(initial, key);
+            callback.mockClear();
+
+            await Onyx.set(key, {phase: 'outer'});
+            await innerWrite;
+
+            expect(callback.mock.calls).toEqual([[inner, key]]);
+        } finally {
+            writer.unsubscribe();
+        }
+    });
+
     it('should restore a key with initial state if the key was set to null and Onyx.clear() is called', () =&gt;
         Onyx.set(ONYX_KEYS.OTHER_TEST, 42)
             .then(() =&gt; Onyx.set(ONYX_KEYS.OTHER_TEST, null))

I looked over the vibe-coded diff and it seems like a substantial simplification. What do you think?

@sosek108

sosek108 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@tgolen thanks for the comments' comments. As non-native I'll take every suggestion with gratitude

@roryabraham Your solution is indeed simpler. And it works - beside the tests I've run this with couple of our derived values POCs and nothing broke.
We were playing safe to not introduce regression but if you're ok with it I'd implement this your way, but we (I and @fabioh8010) would suggest to drop No QA and run some regression tests with this PR.

@roryabraham

Copy link
Copy Markdown
Contributor

@sosek108 that sounds good 👍🏼

Co-authored-by: Rory Abraham <47436092+roryabraham@users.noreply.github.com>
@sosek108
sosek108 force-pushed the hubert/useonyxstate branch from 0b1dc3e to 856e037 Compare November 27, 2026 10:21
@sosek108 sosek108 changed the title [No QA] Add useOnyxState multi-key derived state hook Add useOnyxState multi-key derived state hook Nov 27, 2026
* Returns the frozen collection object for collection
* keys, the cached value for single keys, or `undefined` if not in cache.
*/
getState<TKey extends OnyxKey>(key: TKey): OnyxValue<TKey> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm looking at how OnyxSubscriptionManager has changed on this branch, and one of the simplifications we made was that it just notifies subscribers when keys change, and then they read their value from the cache.

Now, OnyxSubscriptionManager.getState feels out of place. It feels like it should not be the responsibility of the subscription manager, but the cache itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants