Skip to content

regression: URL preview embeds flicker on new messages/reactions (React 19 regression) - #41299

Merged
ggazzo merged 2 commits into
developfrom
fix/oembed-preview-flicker-react19
Jul 10, 2026
Merged

regression: URL preview embeds flicker on new messages/reactions (React 19 regression)#41299
ggazzo merged 2 commits into
developfrom
fix/oembed-preview-flicker-react19

Conversation

@ggazzo

@ggazzo ggazzo commented Jul 10, 2026

Copy link
Copy Markdown
Member

Proposed changes (including videos, screenshots)

Regression (React 19). URL preview embeds (e.g. YouTube iframes) flicker/reload in the message list whenever a new message or a reaction arrives in the room.

TL;DR — pre-existing problems made visible by React 19

The underlying inefficiencies already existed and were harmless-looking under React 18. React 19 changed how dangerouslySetInnerHTML is applied on update: a re-render with a new object literal now re-applies the innerHTML even when the string is identical (React 18 special-cased this prop and compared the __html string, skipping the write). Re-applying innerHTML destroys and recreates the embedded <iframe>, so what used to be an invisible wasted re-render now visibly reloads the embed. This PR fixes both the React-19-visible symptom and the latent causes behind it.

The behavior change comes from React DOM's move to commit-phase diffing — facebook/react #26583 ("Diff properties in the commit phase instead of generating an update payload"). The old diffProperties compared lastProp.__html !== nextProp.__html (string); the new updateProperties/setProp compares each prop value by reference (nextValue === prevValue) and, for dangerouslySetInnerHTML, a fresh { __html } object is never === the previous one, so it always writes domElement.innerHTML.

Root cause

1. Iframe reload on re-render (the React 19 behavior change). OEmbedHtmlPreview passed a fresh { __html } object on every render. Pre-19 this was a no-op (string compare); post-19 the reference compare re-applies innerHTML and reloads the iframe.

2. Re-render storm (pre-existing). A single reaction / new message re-rendered every visible message. Traced to useEmojiPicker, which returned a fresh object literal on every call; ChatAPI assigns it (chat.emojiPicker = useEmojiPicker()) each render, and MessageListProvider reads chat?.emojiPicker as a useMemo dependency. The churning reference rebuilt the MessageListContext value on unrelated updates, re-rendering every consumer (memo cannot guard against context changes). This wasted work already happened under React 18 — it was just invisible; React 19 turned each of those re-renders into an iframe reload. Confirmed via instrumentation: message object refs were unchanged, and the context value flipped only when the emojiPicker dependency changed. After the fix, a reaction re-renders only the changed message (1 vs ~40).

3. Iframe remount on scroll (pre-existing). The virtualized list (virtua) recycles/remounts items on scroll-to-bottom, and URL-preview messages were not covered by keepMounted (only file attachments were). A remount reloads the iframe on any React version — this path was already user-visible before React 19, on scroll.

Fix

  • OEmbedHtmlPreview: memoize the dangerouslySetInnerHTML object so its identity is stable across re-renders; React 19 then skips re-applying the innerHTML.
  • useEmojiPicker / EmojiPickerProvider: memoize the returned object and stabilize close, so chat.emojiPicker stops churning and MessageListContext is no longer rebuilt on every unrelated update — killing the re-render storm at its source.
  • useKeepMountedMessages: keep URL-preview messages mounted in the virtualized list (same treatment as file attachments), so virtua no longer recycles/remounts them on scroll.

Issue(s)

Latent since the message-list virtualization (#40105) and the emoji-picker/context wiring; surfaced as a visible regression by the React 19 upgrade (#40796). Behavior change: facebook/react #26583.

Steps to test or reproduce

  1. Open a room containing a YouTube (or other oembed) URL preview, visible in the viewport.
  2. Send a new message, or add/remove a reaction on any message.
  3. Before: the embed flickers/reloads, and every visible message re-renders. After: the embed stays put; only the changed message re-renders.

Further comments

Draft — fixes verified locally with render instrumentation (reaction now re-renders 1 message instead of ~40). MessageListProvider still re-renders when the list changes (its children change), but its context value is now stable, so consumers no longer cascade — a separate, cheap container re-render left out of scope.

ARCH-2195

https://rocketchat.atlassian.net/browse/CORE-2402

@dionisio-bot

dionisio-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR is ready to merge! 🎉
If you have any trouble, please check the PR guidelines

@changeset-bot

changeset-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 91f74ff

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The changes stabilize OEmbed HTML and emoji-picker references through memoization, and extend message mount preservation to messages containing URL previews.

Changes

Render stability and message mounting

Layer / File(s) Summary
URL preview rendering and mounting
apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx, apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
Sanitized OEmbed HTML is memoized, and messages with URL-preview metadata or headers are kept mounted alongside messages containing files.
Emoji picker reference stability
apps/meteor/client/providers/EmojiPickerProvider/EmojiPickerProvider.tsx, apps/meteor/client/contexts/EmojiPickerContext.ts
The emoji-picker close callback and returned picker object are memoized with matching dependencies.

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

Suggested labels: type: bug

Suggested reviewers: MartinSchoeler, cardoso

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main fix for URL preview embed flicker caused by a React 19 regression.

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.

@ggazzo ggazzo added this to the 8.7.0 milestone Jul 10, 2026
@ggazzo ggazzo changed the title fix: URL preview embeds flicker on new messages/reactions (React 19 regression) regression: URL preview embeds flicker on new messages/reactions (React 19 regression) Jul 10, 2026
ggazzo added 2 commits July 10, 2026 01:59
Under React 19, re-rendering a component that sets dangerouslySetInnerHTML
with a fresh object literal re-applies the innerHTML even when the string is
identical, which reloads embedded iframes (e.g. YouTube). The message list
re-renders every visible message on any store update (reaction, new message),
so every URL-preview iframe reloaded — visible as a flicker.

- Memoize the dangerouslySetInnerHTML object in OEmbedHtmlPreview so its
  identity is stable across re-renders and React skips re-applying it.
- Keep URL-preview messages mounted in the virtualized list (like file
  attachments), so virtua no longer recycles them on scroll-to-bottom and
  remounts the iframe.
useEmojiPicker returned a fresh object literal on every call, and ChatAPI
assigns it (chat.emojiPicker = useEmojiPicker()) each render. MessageListProvider
reads chat?.emojiPicker as a useMemo dependency, so the churning reference
rebuilt the MessageListContext value on unrelated updates (e.g. a reaction),
re-rendering every visible message — memo cannot guard against context changes.

- Memoize the object returned by useEmojiPicker on its stable members.
- Stabilize EmojiPickerProvider's close with useCallback so that memo holds.
@ggazzo
ggazzo force-pushed the fix/oembed-preview-flicker-react19 branch from 4164fc9 to 91f74ff Compare July 10, 2026 05:01
@ggazzo
ggazzo marked this pull request as ready for review July 10, 2026 05:03
@ggazzo
ggazzo requested a review from a team as a code owner July 10, 2026 05:03

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 4 files

Re-trigger cubic

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

🧹 Nitpick comments (3)
apps/meteor/client/contexts/EmojiPickerContext.ts (1)

38-40: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid code comments in implementation per coding guidelines.

The coding guidelines for **/*.{ts,tsx,js} files state to avoid code comments in the implementation. Consider moving this rationale to a commit message or PR description.

As per coding guidelines: "Avoid code comments in the implementation."

🤖 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 `@apps/meteor/client/contexts/EmojiPickerContext.ts` around lines 38 - 40,
Remove the implementation comment explaining stable identity near the emoji
picker context value; retain the underlying memoization behavior and document
the rationale in the commit or PR description instead.

Source: Coding guidelines

apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx (1)

15-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid code comments in implementation per coding guidelines.

The added comments explain React 19 iframe flicker behavior, but the coding guidelines for **/*.{ts,tsx,js} files state to avoid code comments in the implementation. Consider removing these comments or moving the rationale to a commit message or PR description.

As per coding guidelines: "Avoid code comments in the implementation."

🤖 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
`@apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx`
around lines 15 - 18, Remove the explanatory implementation comments above the
memoized dangerouslySetInnerHTML logic in OEmbedHtmlPreview; keep the behavior
unchanged and document the rationale only in the commit or PR description.

Source: Coding guidelines

apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts (1)

6-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid code comments in implementation per coding guidelines.

The coding guidelines for **/*.{ts,tsx,js} files state to avoid code comments in the implementation. Consider moving this rationale to a commit message or PR description.

As per coding guidelines: "Avoid code comments in the implementation."

🤖 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 `@apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts`
around lines 6 - 9, Remove the implementation comment above the keep-mounted
embed logic in useKeepMountedMessages.ts, leaving the behavior unchanged;
preserve the rationale in the commit message or PR description instead.

Source: Coding guidelines

🤖 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.

Nitpick comments:
In
`@apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx`:
- Around line 15-18: Remove the explanatory implementation comments above the
memoized dangerouslySetInnerHTML logic in OEmbedHtmlPreview; keep the behavior
unchanged and document the rationale only in the commit or PR description.

In `@apps/meteor/client/contexts/EmojiPickerContext.ts`:
- Around line 38-40: Remove the implementation comment explaining stable
identity near the emoji picker context value; retain the underlying memoization
behavior and document the rationale in the commit or PR description instead.

In `@apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts`:
- Around line 6-9: Remove the implementation comment above the keep-mounted
embed logic in useKeepMountedMessages.ts, leaving the behavior unchanged;
preserve the rationale in the commit message or PR description instead.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 13a364d3-cfce-4f7f-891a-0fad80787fbc

📥 Commits

Reviewing files that changed from the base of the PR and between 87663fa and 91f74ff.

📒 Files selected for processing (4)
  • apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx
  • apps/meteor/client/contexts/EmojiPickerContext.ts
  • apps/meteor/client/providers/EmojiPickerProvider/EmojiPickerProvider.tsx
  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • GitHub Check: CodeRabbit / Review
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
  • apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx
  • apps/meteor/client/contexts/EmojiPickerContext.ts
  • apps/meteor/client/providers/EmojiPickerProvider/EmojiPickerProvider.tsx
🧠 Learnings (6)
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
  • apps/meteor/client/contexts/EmojiPickerContext.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
  • apps/meteor/client/contexts/EmojiPickerContext.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
  • apps/meteor/client/contexts/EmojiPickerContext.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
  • apps/meteor/client/contexts/EmojiPickerContext.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useKeepMountedMessages.ts
  • apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx
  • apps/meteor/client/contexts/EmojiPickerContext.ts
  • apps/meteor/client/providers/EmojiPickerProvider/EmojiPickerProvider.tsx
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.

Applied to files:

  • apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx
  • apps/meteor/client/providers/EmojiPickerProvider/EmojiPickerProvider.tsx
🪛 ast-grep (0.44.1)
apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx

[warning] 20-20: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation

(react-unsafe-html-injection)

🔇 Additional comments (3)
apps/meteor/client/providers/EmojiPickerProvider/EmojiPickerProvider.tsx (1)

83-84: LGTM!

Also applies to: 101-101, 122-122

apps/meteor/client/contexts/EmojiPickerContext.ts (1)

36-42: Memoization of useEmojiPicker return value is correct.

apps/meteor/client/components/message/content/urlPreviews/OEmbedHtmlPreview.tsx (1)

14-22: No change needed. purifyOptions is module-scoped, so html is the only dependency needed for this memoized sanitizer object.

@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 57.14286% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.97%. Comparing base (87663fa) to head (91f74ff).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41299      +/-   ##
===========================================
- Coverage    69.02%   68.97%   -0.05%     
===========================================
  Files         3755     3755              
  Lines       147152   147167      +15     
  Branches     26313    26348      +35     
===========================================
- Hits        101569   101506      -63     
- Misses       41087    41165      +78     
  Partials      4496     4496              
Flag Coverage Δ
e2e 59.25% <55.55%> (-0.11%) ⬇️
e2e-api 48.94% <ø> (-0.04%) ⬇️
unit 70.49% <50.00%> (-0.04%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Jul 10, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Jul 10, 2026
@dionisio-bot
dionisio-bot Bot added this pull request to the merge queue Jul 10, 2026
@ggazzo
ggazzo removed this pull request from the merge queue due to a manual request Jul 10, 2026
@dionisio-bot
dionisio-bot Bot added this pull request to the merge queue Jul 10, 2026
@ggazzo
ggazzo removed this pull request from the merge queue due to a manual request Jul 10, 2026
@ggazzo
ggazzo merged commit 6f85f55 into develop Jul 10, 2026
47 of 48 checks passed
@ggazzo
ggazzo deleted the fix/oembed-preview-flicker-react19 branch July 10, 2026 12:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stat: QA assured Means it has been tested and approved by a company insider stat: ready to merge PR tested and approved waiting for merge type: bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants