Skip to content

fix: stop useSubscriptions re-querying on connection state changes - #7559

Open
deepak0x wants to merge 5 commits into
RocketChat:masterfrom
deepak0x:fix/7437-roomlist-flicker-connection
Open

fix: stop useSubscriptions re-querying on connection state changes#7559
deepak0x wants to merge 5 commits into
RocketChat:masterfrom
deepak0x:fix/7437-roomlist-flicker-connection

Conversation

@deepak0x

@deepak0x deepak0x commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

useSubscriptions selected the entire state.server object and listed it in the useEffect dependency array. state.server holds connection-state fields (connecting, loading, connected) that change on every transition, so each transition produced a new object reference and re-ran the effect. That re-subscribed and re-queried WatermelonDB on every connection change, making the room list flicker.

The selected server value was never used inside the effect body, so this removes the unused selector and its dependency. The query now only re-runs when subscription-relevant preferences actually change.

Issue(s)

Fixes #7437

How to test or reproduce

  1. Open the app and observe the room list in RoomsListView.
  2. Before this fix: toggling the connection state (e.g. connecting → connected, or loading → not loading) re-triggers the useSubscriptions effect and re-queries the database, causing the room list to flicker on every connection change.
  3. After this fix: the effect no longer depends on state.server, so connection transitions don't re-query and the list stays stable.

Regression test added: app/views/RoomsListView/hooks/useSubscriptions.test.tsx renders a harness using the hook with a mock store and a mocked database, then dispatches two state.server connection-state transitions and asserts the database query is not re-run. It failed before the fix (the query ran on each transition) and passes after.

Screenshots

N/A (behavior only, no visual change).

Types of changes

  • Bugfix (non-breaking change which fixes an issue)

Checklist

  • I have read the CONTRIBUTING doc
  • I have signed the CLA
  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works (if applicable)
  • I have added necessary documentation (if applicable)
  • Any dependent changes have been merged and published in downstream modules

Further comments

The fix is minimal and scoped: only the unused server selector (and its entry in the dependency array) is removed. No other behavior of the hook changes.

Summary by CodeRabbit

  • Bug Fixes

    • Improved room subscription handling across server connection state changes.
    • Prevented unnecessary database queries while connection or loading states update.
    • Maintained consistent subscription loading and room grouping behavior for a stable room list experience.
  • Tests

    • Added coverage verifying that connection and loading state changes do not trigger additional database queries.
    • Confirmed existing subscription behavior remains intact during server state transitions.

useSubscriptions selected the entire state.server object and listed it in
the useEffect dependency array. state.server holds connection-state fields
(connecting/loading/connected) that change on every transition, producing a
new object reference and re-running the effect, which re-subscribes and
re-queries WatermelonDB on each connection change and makes the room list
flicker.

The selected server value was never used inside the effect, so remove the
unused selector and its dependency. The query now only re-runs when the
subscription-relevant preferences actually change.

Fixes RocketChat#7437

Signed-off-by: Deepak Bhagat <deepak988088@gmail.com>
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9fbe93b8-5958-4e8a-ae1d-7328c1010068

📥 Commits

Reviewing files that changed from the base of the PR and between ecf8ab4 and abb08dc.

📒 Files selected for processing (1)
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx

Walkthrough

useSubscriptions now selects only state.server.server. A Redux-based test verifies that connection and loading state changes do not trigger additional database queries.

Changes

Subscription query stability

Layer / File(s) Summary
Narrow server selector
app/views/RoomsListView/hooks/useSubscriptions.ts
useSubscriptions reads the nested server value instead of the full server state object.
Validate query stability
app/views/RoomsListView/hooks/useSubscriptions.test.tsx
A Redux harness and mocked database verify that connection and loading state changes do not increase subscription query calls.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested labels: type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main fix: preventing useSubscriptions from re-querying when connection state changes.
Linked Issues check ✅ Passed The selector change and regression test satisfy issue #7437 by preventing connection-state re-queries while preserving server-change subscriptions.
Out of Scope Changes check ✅ Passed The selector update and focused regression test are directly related to issue #7437, with no unrelated code changes identified.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
app/views/RoomsListView/hooks/useSubscriptions.test.tsx (1)

39-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add explicit return annotations to the test functions.

Add a return type to rootReducer and Harness. Keep the fixture partial. Do not cast it to IApplicationState.

As per coding guidelines, TypeScript functions require explicit parameter and return annotations. Based on learnings, partial selector fixtures must not require IApplicationState.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/views/RoomsListView/hooks/useSubscriptions.test.tsx` around lines 39 -
45, Update rootReducer and Harness with explicit TypeScript parameter and return
type annotations, while keeping the fixture state partial and avoiding any cast
to IApplicationState.

Sources: Coding guidelines, Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/views/RoomsListView/hooks/useSubscriptions.test.tsx`:
- Line 7: Remove the unused database import from useSubscriptions.test.tsx; keep
any jest.mock usage unchanged, since it does not require a local database
binding.
- Around line 48-74: Update the test around Harness and getSubscriptions to be
asynchronous, awaiting the initial subscription setup after render so
queryCallCount reflects observeWithColumns. After each UPDATE_SERVER dispatch,
wait for the related effect work to settle before asserting that queryCallCount
remains equal to initialCalls.

In `@app/views/RoomsListView/hooks/useSubscriptions.ts`:
- Line 126: Update the dependency array of the subscription effect in
useSubscriptions to include the stable active database/server identity used by
database.active, so changing the active database re-subscribes and stops using
the previous database’s emissions. Add a test that switches the active database
or server identity and verifies the subscription is refreshed.

---

Nitpick comments:
In `@app/views/RoomsListView/hooks/useSubscriptions.test.tsx`:
- Around line 39-45: Update rootReducer and Harness with explicit TypeScript
parameter and return type annotations, while keeping the fixture state partial
and avoiding any cast to IApplicationState.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3908eeb0-0c5d-4b19-9ef5-ea051c3f83e9

📥 Commits

Reviewing files that changed from the base of the PR and between 347b61d and db25a33.

📒 Files selected for processing (2)
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
  • app/views/RoomsListView/hooks/useSubscriptions.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

Files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: Format JavaScript and TypeScript code with Oxfmt using the repository configuration: tabs, single quotes, 130-character width, no trailing commas, omitted arrow-function parentheses where possible, and same-line brackets.
Follow Oxlint rules configured in .oxlintrc.json, including the import, React, Jest, TypeScript, and React Native plugins.

Files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
🧠 Learnings (4)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
📚 Learning: 2026-06-24T22:58:43.390Z
Learnt from: Rohit3523
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7157
File: app/views/MessagesView/index.tsx:392-392
Timestamp: 2026-06-24T22:58:43.390Z
Learning: When wrapping a React Native component (e.g., via `withSafeAreaInsets`) ensure `hoistNonReactStatics` is only required if the wrapped component actually defines static properties/methods that consumers rely on. If the component has no statics (as in `app/views/MessagesView/index.tsx`), you can omit `hoistNonReactStatics` for this case.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
📚 Learning: 2026-06-25T18:37:25.526Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.test.tsx:16-22
Timestamp: 2026-06-25T18:37:25.526Z
Learning: In Rocket.Chat ReactNative tests that mock selectors for `useAppSelector`, don’t require the mocked selector input to be typed as `IApplicationState` when the fixture only includes a partial Redux state slice (e.g., only `server` and `settings`). Requiring the full `IApplicationState` type in that scenario forces unsafe `as IApplicationState` casts and undermines type-safety. For these narrowly scoped selector-mock fixtures, use a less strict type (e.g., `any`) to keep the mock focused on the slice under test.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
📚 Learning: 2026-06-25T18:37:44.793Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.tsx:101-141
Timestamp: 2026-06-25T18:37:44.793Z
Learning: In the Rocket.Chat React Native codebase, do not treat passing an `async` function directly to an event prop in React/React Native UI components (e.g., `onPress={async () => ...}` in TSX) as a “floating promises” CI-blocking lint issue—this repo does not enable the ESLint `no-floating-promises` rule (while `no-void` is enforced). Only raise robustness follow-ups when there are genuinely unhandled promise paths (e.g., fire-and-forget calls like `save()` that return a Promise that is neither awaited nor handled), and prefer making sure failure paths are explicitly handled/reported rather than blocking on lint-style floating-promise concerns.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
🪛 ESLint
app/views/RoomsListView/hooks/useSubscriptions.test.tsx

[error] 7-7: 'database' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 7-7: Missing file extension for "../../lib/database"

(import/extensions)

Comment thread app/views/RoomsListView/hooks/useSubscriptions.test.tsx Outdated
Comment thread app/views/RoomsListView/hooks/useSubscriptions.test.tsx Outdated
Comment thread app/views/RoomsListView/hooks/useSubscriptions.ts Outdated
Removes the unused database import flagged by Oxlint (no-unused-vars and
import/extensions). jest.mock does not require a local binding.

Signed-off-by: Deepak Bhagat <deepak988088@gmail.com>
@deepak0x

deepak0x commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit finding in the latest push: removed the unused database import from useSubscriptions.test.tsx (jest.mock does not require a local binding), clearing the Oxlint no-unused-vars / import/extensions errors.

Address CodeRabbit review on RocketChat#7559:
- depend on state.server.server (the active server URL) instead of the entire
  state.server object. Connection-state transitions (connecting/loading) no
  longer re-run the effect, fixing the room-list flicker, while an actual
  server switch (which changes the URL and the underlying database.active)
  still re-subscribes correctly.
- make the regression test async: wait for the initial subscription setup
  after render and wait for async work to settle after each dispatched
  connection-state change before asserting the query count is unchanged.

Signed-off-by: Deepak Bhagat <deepak988088@gmail.com>
… aware

Wait for the initial async subscription setup after render and for async
work to settle after each dispatched connection-state change before asserting
the query count is unchanged. Use state.server.server (active server URL) in
the mock store to match the updated selector.

Signed-off-by: Deepak Bhagat <deepak988088@gmail.com>
@deepak0x

deepak0x commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the two additional CodeRabbit findings in the latest push:

  • Major (re-subscribe on active DB identity change): the hook no longer depends on the entire state.server object. It now selects state.server.server (the active server URL), which is stable across connection-state transitions but changes when the underlying database.active switches during a real server change. So connection flicker is fixed AND an actual server switch still re-subscribes correctly (no regression).
  • Minor (async test timing): the regression test is now async — it waitFors the initial subscription setup after render and waitFors async work to settle after each dispatched connection-state change before asserting the query count is unchanged, and the mock uses database.active to match the accessor.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/views/RoomsListView/hooks/useSubscriptions.test.tsx`:
- Around line 61-66: Remove the unnecessary async keyword from both act
callbacks surrounding the synchronous store.dispatch calls in the subscription
test, including the UPDATE_SERVER dispatch blocks around lines 61 and 68, while
preserving the existing act wrapping and dispatch behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 03f52e65-436f-4b16-ba11-75c9aa7ad220

📥 Commits

Reviewing files that changed from the base of the PR and between d67eb20 and ecf8ab4.

📒 Files selected for processing (2)
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
  • app/views/RoomsListView/hooks/useSubscriptions.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

Files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: Format JavaScript and TypeScript code with Oxfmt using the repository configuration: tabs, single quotes, 130-character width, no trailing commas, omitted arrow-function parentheses where possible, and same-line brackets.
Follow Oxlint rules configured in .oxlintrc.json, including the import, React, Jest, TypeScript, and React Native plugins.

Files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
🧠 Learnings (4)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.ts
  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
📚 Learning: 2026-06-24T22:58:43.390Z
Learnt from: Rohit3523
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7157
File: app/views/MessagesView/index.tsx:392-392
Timestamp: 2026-06-24T22:58:43.390Z
Learning: When wrapping a React Native component (e.g., via `withSafeAreaInsets`) ensure `hoistNonReactStatics` is only required if the wrapped component actually defines static properties/methods that consumers rely on. If the component has no statics (as in `app/views/MessagesView/index.tsx`), you can omit `hoistNonReactStatics` for this case.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
📚 Learning: 2026-06-25T18:37:25.526Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.test.tsx:16-22
Timestamp: 2026-06-25T18:37:25.526Z
Learning: In Rocket.Chat ReactNative tests that mock selectors for `useAppSelector`, don’t require the mocked selector input to be typed as `IApplicationState` when the fixture only includes a partial Redux state slice (e.g., only `server` and `settings`). Requiring the full `IApplicationState` type in that scenario forces unsafe `as IApplicationState` casts and undermines type-safety. For these narrowly scoped selector-mock fixtures, use a less strict type (e.g., `any`) to keep the mock focused on the slice under test.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
📚 Learning: 2026-06-25T18:37:44.793Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.tsx:101-141
Timestamp: 2026-06-25T18:37:44.793Z
Learning: In the Rocket.Chat React Native codebase, do not treat passing an `async` function directly to an event prop in React/React Native UI components (e.g., `onPress={async () => ...}` in TSX) as a “floating promises” CI-blocking lint issue—this repo does not enable the ESLint `no-floating-promises` rule (while `no-void` is enforced). Only raise robustness follow-ups when there are genuinely unhandled promise paths (e.g., fire-and-forget calls like `save()` that return a Promise that is neither awaited nor handled), and prefer making sure failure paths are explicitly handled/reported rather than blocking on lint-style floating-promise concerns.

Applied to files:

  • app/views/RoomsListView/hooks/useSubscriptions.test.tsx
🪛 ESLint
app/views/RoomsListView/hooks/useSubscriptions.test.tsx

[error] 61-61: Async arrow function has no 'await' expression.

(require-await)


[error] 68-68: Async arrow function has no 'await' expression.

(require-await)

🔇 Additional comments (2)
app/views/RoomsListView/hooks/useSubscriptions.ts (1)

42-42: LGTM!

Also applies to: 127-127

app/views/RoomsListView/hooks/useSubscriptions.test.tsx (1)

2-2: LGTM!

Also applies to: 32-32, 47-47, 56-59, 75-77

Comment thread app/views/RoomsListView/hooks/useSubscriptions.test.tsx
Use the correct relative path (../../../lib/database) matching the source
import so jest can resolve the module mock.

Signed-off-by: Deepak Bhagat <deepak988088@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant