Component rendering and hydration
React on Rails turns Rails view output into live React islands in the browser. Rails supplies the component name, props, mount id, and page context; the client finds the registered component, then either hydrates server HTML or creates a new React root. The path also connects page navigation events to cleanup, so mounts do not survive a page swap.
The wider Rails boundary is described in Rails integration, while registration and bundle setup are covered by JavaScript runtime and registration. Server output and its client handoff are covered by server rendering protocol.
Rails-to-browser rendering contract
Component metadata
The react_component view helper emits a component specification next to the mount element. The specification carries the registered component name, the DOM id to mount into, JSON props, trace state, hydration mode, and any declared store dependencies. The Rails helper also emits one page-level js-react-on-rails-context JSON script so every client render can use request and environment data (react_on_rails/…/pro_helper.rb• L5-41, react_on_rails/…/helper.rb• L764-795).
The mount element's inner HTML is the signal for the client to choose hydration. Rails may leave it empty for client-only rendering, or fill it with server-rendered HTML for hydration. The specification remains present in both cases, which lets one client path support both modes (packages/…/ClientRenderer.ts• L426-514).
References: react_on_rails/…/pro_helper.rb• L5-41 react_on_rails/…/helper.rb• L664-795 packages/…/ClientRenderer.ts• L426-514
Rails context and props
The browser reads the page context from #js-react-on-rails-context and parses the specification's text as component props. The context identifies the Rails environment and request, and can also carry integration data such as the CSP nonce or server-component information. A missing or invalid context stops the client render path rather than producing a partial mount (packages/…/context.ts• L10-37, react_on_rails/…/helper.rb• L344-413).
Store data follows the same Rails-to-browser handoff. A full page load initializes the stores declared in the page; an on-demand component load uses that island's data-store-dependencies when available. This keeps unrelated store elements out of a targeted render while preserving the older all-stores behavior for hand-written or legacy markup (packages/…/ClientRenderer.ts• L119-182, packages/…/ClientRenderer.ts• L555-615).
References: packages/…/context.ts• L10-37 react_on_rails/…/helper.rb• L344-413 packages/…/ClientRenderer.ts• L119-182 packages/…/ClientRenderer.ts• L555-615
Component resolution and root creation
Component lookup
The client uses the metadata's component name as a key into the ComponentRegistry. Registration records whether the value is a normal React component, a two-argument render function, or a three-argument renderer that owns its own mount. A missing name fails with the registered-name list, which makes bundle order and registration errors visible (packages/…/ComponentRegistry.ts• L6-54).
For normal components, the client creates a React element from the registered value and the Rails props. A render function can first produce a component or another supported render result. A renderer is different: it receives the props, Rails context, and DOM id, then controls its own DOM work instead of going through the framework's React root (packages/…/createReactOutput.ts• L30-50, packages/…/createReactOutput.ts• L61-150, packages/…/index.ts• L232-243).
References: packages/…/ComponentRegistry.ts• L6-54 packages/…/createReactOutput.ts• L30-50 packages/…/createReactOutput.ts• L61-150 packages/…/index.ts• L232-243
Hydration and client rendering
The client chooses hydration when the target already contains HTML. It chooses a fresh render when the target is empty. reactHydrateOrRender hides the React version split: React 18 and later use hydrateRoot or createRoot, while React 16 and 17 use the legacy hydrate or render APIs (packages/…/ClientRenderer.ts• L480-514, packages/…/reactHydrateOrRender.ts• L6-15, packages/react-on-rails/src/reactApis.cts#L15-L24, packages/react-on-rails/src/reactApis.cts#L75-L90).
The normal sequence is:
flowchart TD
A[page or component loaded] --> B[read Rails context]
B --> C[read component metadata and props]
C --> D[find registered component]
D --> E{target has HTML?}
E -->|yes| F[hydrate existing HTML]
E -->|no| G[create and render a root]
F --> H[track mount]
G --> H
The client tracks framework-created roots by DOM id. A repeat call for the same connected target is skipped, which prevents a second hydration attempt. If the target node was replaced, the old mount is cleaned up before the new target is rendered (packages/…/ClientRenderer.ts• L435-469, packages/…/ClientRenderer.ts• L501-514).
References: packages/…/ClientRenderer.ts• L435-469 packages/…/ClientRenderer.ts• L480-514 packages/…/reactHydrateOrRender.ts• L6-15 packages/…/reactApis.cts• L15-24 packages/…/reactApis.cts• L75-90
Hydration scheduling
Rails can mark an island for immediate, visible, or idle hydration. Immediate mode mounts during the load call. Visible mode waits for an observable target near the viewport; idle mode waits for browser idle time. If a browser lacks the needed scheduling API, the client uses a short timer fallback (react_on_rails/…/render_options.rb• L7-24, packages/…/ClientRenderer.ts• L189-278).
Scheduling is part of the mount state. A pending visible observer or idle callback is canceled when the page changes, and a detached or replaced target cannot later mount an orphaned root. This keeps delayed hydration aligned with the current DOM (packages/…/ClientRenderer.ts• L522-543, packages/…/ClientRenderer.ts• L629-655).
References: react_on_rails/…/render_options.rb• L7-24 packages/…/ClientRenderer.ts• L189-278 packages/…/ClientRenderer.ts• L522-543 packages/…/ClientRenderer.ts• L629-655
Renderer-owned mounts
A three-argument renderer owns the mount instead of returning a React element to the framework. It may return { teardown } so the client can release that mount later. A bare return value keeps the legacy no-cleanup behavior and is not treated as a teardown (packages/…/ClientRenderer.ts• L316-345, packages/…/rendererTeardown.ts• L1-12, packages/…/index.ts• L193-217).
The client records a renderer mount as soon as the renderer runs. It later attaches a synchronous or asynchronous teardown when one is returned. This contract covers custom React roots, event listeners, and other resources that the framework cannot unmount itself (packages/…/ClientRenderer.ts• L351-419).
References: packages/…/ClientRenderer.ts• L316-345 packages/…/ClientRenderer.ts• L351-419 packages/…/rendererTeardown.ts• L1-12 packages/…/index.ts• L193-217
Page lifecycle integration
Client startup
The client bundle builds the ReactOnRails global and then registers one page-loaded callback. Core rendering waits until the document reaches a safe load point so deferred scripts can register components before the first sweep. The global guard prevents more than one bundle startup on the page (packages/…/ReactOnRails.client.ts• L1-18, packages/…/clientStartup.ts• L7-30).
The page-loaded callback initializes stores and renders every .js-react-on-rails-component element. A caller can use reactOnRailsComponentLoaded(domId) after asynchronous content arrives to initialize only one island. The on-demand path is also useful when a navigation system inserts HTML after the first page sweep (packages/…/ClientRenderer.ts• L551-625).
References: packages/…/ReactOnRails.client.ts• L1-18 packages/…/clientStartup.ts• L7-30 packages/…/ClientRenderer.ts• L551-625
Navigation events
pageLifecycle provides a common loaded and unloaded event model for plain browser loads, Turbo, and Turbolinks. It waits for DOMContentLoaded or the later complete state before the initial setup, which avoids racing deferred component bundles. It then maps navigation events to the same callbacks (packages/…/pageLifecycle.ts• L17-59, packages/…/pageLifecycle.ts• L61-114).
This event bridge is the connection between Rails navigation and the React mount registry. A before-render event runs unload callbacks before Turbo or Turbolinks swaps the page; the following render event runs the page-loaded sweep for the new HTML. See Rails engine and configuration for the Rails-side setup that enables this boundary.
References: packages/…/pageLifecycle.ts• L17-59 packages/…/pageLifecycle.ts• L61-114 packages/…/clientStartup.ts• L28-30
Rendering errors and diagnostics
Client render failures
Errors from lookup, prop parsing, element creation, or immediate mount are normalized into a ReactOnRails error that names the component. The original value is logged and retained as the cause, so non-Error throws and the original stack remain useful. Delayed hydration reports the same failure inside the scheduler instead of throwing out of an observer or idle callback (packages/…/ClientRenderer.ts• L281-308, packages/…/ClientRenderer.ts• L516-547).
Trace metadata adds the component name, DOM id, props, and Rails context to browser logs. Use development and diagnostics for the broader diagnostic tools and the expected investigation path.
References: packages/…/ClientRenderer.ts• L281-308 packages/…/ClientRenderer.ts• L426-547 packages/…/createReactOutput.ts• L69-150
React root error callbacks
React root errors can be sent to callbacks registered through ReactOnRails.setOptions({ rootErrorHandlers }). The client adds the component name and DOM id to each callback. React 18 supports recoverable errors; React 19 adds caught and uncaught root errors (packages/…/rootErrorHandlers.ts• L28-120, packages/…/index.ts• L439-490).
Hydration mismatches are recoverable React errors. In Rails development mode, the client preserves React's default error report and adds a message with the affected island and a link to the hydration guide. User callbacks are captured when the root is created, so later option changes affect new roots only (packages/…/rootErrorHandlers.ts• L172-235, packages/…/rootErrorHandlers.ts• L281-360).
References: packages/…/rootErrorHandlers.ts• L28-120 packages/…/rootErrorHandlers.ts• L172-235 packages/…/rootErrorHandlers.ts• L281-360 packages/…/index.ts• L439-490
Mount teardown
Root cleanup
The client keeps a mount record for each framework root, renderer-owned mount, or delayed render. On page unload it unmounts React roots, invokes renderer teardowns, cancels delayed work, and clears the records. The same cleanup also runs when a new node replaces an old node with the same DOM id (packages/…/ClientRenderer.ts• L45-61, packages/…/ClientRenderer.ts• L84-117, packages/…/ClientRenderer.ts• L629-655).
Cleanup continues after one entry fails. Synchronous teardown errors are logged, and rejected asynchronous teardown promises are handled so they do not become unhandled browser errors. The core client cannot recover a renderer teardown that resolves after its mount was already removed; React on Rails Pro provides the stronger async-renderer cleanup path (packages/…/ClientRenderer.ts• L63-104, packages/…/ClientRenderer.ts• L351-419).
References: packages/…/ClientRenderer.ts• L45-117 packages/…/ClientRenderer.ts• L351-419 packages/…/ClientRenderer.ts• L629-655
Store cleanup
Hydrated stores live for one page lifecycle so repeated component-load calls reuse the same store instance. Page unload clears hydrated stores after mounts are released, which allows the next Rails page to create stores from its own props (packages/…/ClientRenderer.ts• L119-145, packages/…/ClientRenderer.ts• L644-656, packages/…/StoreRegistry.ts• L35-66, packages/…/StoreRegistry.ts• L86-100).
References: packages/…/ClientRenderer.ts• L119-145 packages/…/ClientRenderer.ts• L644-656 packages/…/StoreRegistry.ts• L35-66 packages/…/StoreRegistry.ts• L86-100
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the Rails
data-*attributes in react_on_rails/…/pro_helper.rb aligned with the reads in packages/…/ClientRenderer.ts. - Keep
RailsContextfields in packages/…/index.ts aligned with the object built byrails_contextin react_on_rails/…/helper.rb. - Keep the DOM id and component-name contract consistent across the Rails helper, component registry lookup, and any on-demand caller.
- When changing root creation, preserve the React 16/17 legacy path and the React 18+ root path, including the error callback options.
- When changing navigation events, preserve unload-before-render ordering so React roots, renderer mounts, delayed work, and stores are cleared before the next page is initialized.
- When changing store metadata, preserve the targeted-render fallback for markup without valid
data-store-dependencies. - When changing renderer return values, preserve the explicit
{ teardown }wrapper so legacy renderer return values are not mistaken for cleanup callbacks.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A component bundle has not registered the name when the page sweep runs | Lookup fails and the island does not render | Initial startup waits for DOMContentLoaded or complete; keep deferred bundle order safe (packages/…/pageLifecycle.ts• L70-97). |
| Rails emits a name or DOM id that differs from the registered component or target node | The client cannot find the component or mount target | Treat the Rails metadata and registry name as one contract (react_on_rails/…/pro_helper.rb• L10-23, packages/…/ComponentRegistry.ts• L45-54). |
| Server HTML differs from the client output | React reports a recoverable hydration error and may discard the server HTML | Use matching props and render conditions; enable development diagnostics or onRecoverableError (packages/…/rootErrorHandlers.ts• L227-235). |
| The same island is rendered again after its node was replaced | The old root or renderer mount can leak, or the new node can stay inactive | The client compares the tracked node reference and cleans the old entry before rendering the replacement (packages/…/ClientRenderer.ts• L441-469). |
| A renderer's async teardown resolves after navigation or node replacement | Core drops the stale teardown and the renderer-owned mount may leak | Return a synchronous teardown when possible; use React on Rails Pro when async teardown must survive fast navigation (packages/…/ClientRenderer.ts• L386-399). |
| A store generator is missing during a targeted render | Store setup logs the issue; the component fails later if it actually reads that store | Register store generators before loading the component bundle and use the declared dependency names (packages/…/ClientRenderer.ts• L573-595, packages/…/StoreRegistry.ts• L73-83). |
Key files
| File | Why to read it |
|---|---|
| react_on_rails/…/pro_helper.rb | Defines the metadata and inline load signal that Rails places beside each component. |
| react_on_rails/…/helper.rb | Defines page context, server-rendered mount output, and the Rails-side handoff. |
| react_on_rails/…/render_options.rb | Defines the high-level render and hydration options accepted by the Rails helper. |
| packages/…/ClientRenderer.ts | Provides the main browser path from metadata to lookup, mount, scheduling, tracking, and cleanup. |
| packages/…/ComponentRegistry.ts | Shows how names map to components and renderer roles. |
| packages/…/createReactOutput.ts | Shows how a registered value becomes a React element or a renderer delegation. |
| packages/…/reactHydrateOrRender.ts | Shows the single boundary between hydration and client rendering. |
| packages/…/pageLifecycle.ts | Shows how browser load, Turbo, and Turbolinks events drive render and teardown. |
| packages/…/rootErrorHandlers.ts | Shows root error reporting and hydration-mismatch diagnostics. |
| packages/…/StoreRegistry.ts | Shows store generator registration, page-scoped hydrated stores, and missing-store errors. |