Surfaces in your app
How to work with a surface after it is on screen: change its props, close it, watch its state, and recover from a failure.
This page assumes the artifact is already in your app and the runtime is started. If not, do the Quickstart first. The examples use the artifact ShopReact and its surface PointsHistory.
Full screen or embedded
Section titled “Full screen or embedded”A host is the native container that shows one surface. There are two kinds, and each generated surface type builds both.
| Full screen | Embedded | |
|---|---|---|
| Use it for | A whole screen on your navigation stack | A block inside a native screen: a card, a banner, a list row |
| iOS | PointsHistory.viewController(...)returns a SurfaceViewController |
PointsHistory.view(...)returns a SurfaceHostView |
| Android | PointsHistory.fragment(...)returns a SurfaceFragment |
PointsHistory.view(context, ...)returns a SurfaceHostView |
| Opens when | iOS: the view loads. Android: the fragment’s view is created. |
The view enters a window for the first time. |
| Size | Fills the view controller or fragment | You set it. The view does not report the size of its content. |
Both kinds have the same members: descriptor, state, updateProps, retry, close, a delegate or listener, and a fallback view. Everything on this page works the same for both.
// Full screenlet screen = PointsHistory.viewController( userId: "42", filter: .lastMonth, compact: false)navigationController? .pushViewController(screen, animated: true)
// Embeddedlet block = PointsHistory.view( userId: "42", compact: true)stackView.addArrangedSubview(block)// Full screenval screen = PointsHistory.fragment( userId = "42", compact = false)supportFragmentManager.beginTransaction() .replace(R.id.content, screen) .addToBackStack(null) .commit()
// Embeddedval block = PointsHistory.view( context, userId = "42", compact = true)block.id = R.id.points_blockcontainer.addView(block)Three rules hold for every host:
- A host opens once. Taking the view out of the window and putting it back does not mount the surface again.
- A hidden surface stays alive. When another screen covers it, when the app goes to the background, or when Android destroys the view of a fragment on the back stack, the surface keeps its state. It is still
livewhen the user comes back. - Use the main thread. Every host member is main-thread only.
Update props
Section titled “Update props”When your native state changes, send new props to an open surface. The surface renders again with the new values. It does not remount, so it keeps its React state. Build the props with the generated props function so they stay typed.
try screen.updateProps( PointsHistory.props(userId: "42", filter: .all, compact: true))block.updateProps( PointsHistory.props( userId = "42", filter = PointsHistory.Filter.ALL, compact = true))You pass the full set of props each time, not only the ones that changed.
The props are checked at once. Props larger than 16 KB, or a number that is not finite, throw an error: SurfaceDescriptorError on iOS and IllegalArgumentException on Android. The surface keeps its previous props and its state.
| State of the surface | What updateProps does |
|---|---|
live |
The surface renders with the new props and stays live. |
described or mounting |
The props are stored and used when the surface mounts. |
failed |
The props are kept. The next retry() mounts with them. |
closed |
Nothing. The call is ignored and does not throw. |
Close a surface
Section titled “Close a surface”Closing unmounts the React tree and frees what the host holds. Most of the time you do not call anything: a host closes itself when it goes away for good.
| Host | Closes by itself when |
|---|---|
| iOS, both kinds | The host is released. Removing an embedded view from its window does not close it. |
Android SurfaceFragment |
The fragment is removed for good, or its Activity finishes. A rotation or a trip to the back stack does not close it. |
Android SurfaceHostView |
The Activity or fragment view that owns it is destroyed, except on a configuration change. Detaching the view alone does not close it. |
Call close() yourself when you want the surface gone before that, for example when you hide a banner and keep the screen.
block.close()block.removeFromSuperview()block.close()container.removeView(block)close() is safe to call more than once, and it is final. A closed host never opens again and ignores updateProps and retry. To show the surface again, create a new host.
Observe state
Section titled “Observe state”Every host has a state you can read, and it reports each change to its delegate (iOS) or listener (Android).
described mounting live failed closed
| State | Meaning |
|---|---|
described |
The host exists and knows which surface to show. Nothing is loading yet. This is the first state. |
mounting |
The host opened. The runtime boots if it has not yet, then React mounts the surface. |
live |
The first React render is on screen. Props updates keep the surface live. |
failed |
The surface could not load or render. The state carries a failure with a cause. The container is empty or shows your fallback view. |
closed |
The end. The surface is unmounted. |
The type also has a suspended state. It is reserved and no host reports it today, so you only need a default branch for it.
final class PointsScreen: UIViewController, SurfaceHostDelegate { func surfaceHost(_ host: any SurfaceHost, didChange state: SurfaceState) { switch state { case .live: spinner.stopAnimating() case .failed(let failure): log("failed: \(failure.cause): \(failure.message)") default: break } } func surfaceHost(_ host: any SurfaceHost, didReport timings: SurfaceTimings) { log("mount: \(timings.mount.outcome)") }}
screen.delegate = pointsScreenblock.listener = object : SurfaceHostListener { override fun onSurfaceStateChanged(host: SurfaceHost, state: SurfaceState) { when (state) { is SurfaceState.Live -> spinner.hide() is SurfaceState.Failed -> Log.w("app", "failed: ${state.failure.cause}: ${state.failure.message}") else -> Unit } } override fun onSurfaceTimings(host: SurfaceHost, timings: SurfaceTimings) { Log.i("app", "mount: ${timings.mount.outcome}") }}- Timings. Each host reports its timings once, when it reaches
liveorfailed: the boot stages it paid for and its own mount. On iOS you must implement both delegate methods. On Android the timings method is optional. - iOS keeps the delegate weakly. Keep your own reference to it, or it is released and the calls stop.
- Callbacks arrive on the main thread, in order.
- Commands from a callback run a moment later. If you call
retry(),close()orupdatePropsfrom inside a callback, the command runs on the next turn of the main loop, not inside the callback. Sohost.statehas not changed yet on the next line.updatePropsstill checks the props and throws at once.
Handle a failure
Section titled “Handle a failure”When a surface cannot load or its React code throws while rendering, the host moves to failed. Your app keeps running, and surfaces that are already live are not affected. You decide what the user sees and whether to try again.
Show a fallback
Section titled “Show a fallback”Give the host a native view to show while it is failed. Without one, the container is empty.
screen.fallbackView = MyErrorView()block.fallbackViewFactory = { context, failure -> MyErrorView(context, failure)}The host shows the fallback when it enters failed and removes it when it leaves that state. On Android you give a factory instead of a view, and it receives the failure so the view can show a message that fits the cause.
Retry, with a limit
Section titled “Retry, with a limit”retry() mounts the same surface again in the same host, with the same id and its latest props. It does nothing unless the host is failed.
This delegate retries twice for the causes where a retry can help, and gives up for the others. When it gives up it does nothing, so the host stays failed and the fallback stays on screen.
final class HomeViewController: UIViewController, SurfaceHostDelegate { private var retries: [String: Int] = [:] // per surface id private let maxRetries = 2
func surfaceHost(_ host: any SurfaceHost, didChange state: SurfaceState) { let id = host.descriptor.id switch state { case .live, .closed: retries[id] = nil // a healthy mount resets the budget case .failed(let failure): switch failure.cause { case .bundleMissing, .fingerprintMismatch, .duplicateSurfaceId: break // a retry cannot help: keep the fallback case .renderException, .evaluationError, .surfaceNotRegistered: let used = retries[id, default: 0] guard used < maxRetries else { return } // give up: keep the fallback retries[id] = used + 1 host.retry() @unknown default: break // a cause added in a later version } default: break } }
func surfaceHost(_ host: any SurfaceHost, didReport timings: SurfaceTimings) {}}class HomeActivity : AppCompatActivity(), SurfaceHostListener { private val retries = mutableMapOf<String, Int>() // per surface id private val maxRetries = 2
override fun onSurfaceStateChanged(host: SurfaceHost, state: SurfaceState) { val id = host.descriptor.id when (state) { is SurfaceState.Live, is SurfaceState.Closed -> retries.remove(id) // a healthy mount resets the budget is SurfaceState.Failed -> when (state.failure.cause) { is SurfaceFailureReason.BundleMissing, is SurfaceFailureReason.FingerprintMismatch, is SurfaceFailureReason.DuplicateSurfaceId -> Unit // a retry cannot help else -> { val used = retries[id] ?: 0 if (used >= maxRetries) return // give up: keep the fallback retries[id] = used + 1 host.retry() } } else -> Unit } }}- Calling
retry()from the callback is safe. It runs on the next turn of the main loop, so it never recurses. - Do not call
close()to give up if you want the fallback to stay. Closing a host removes its fallback. Close it when the user leaves the screen. - You can also offer a manual retry: put a button in your fallback view that calls
host.retry().
Failure causes
Section titled “Failure causes”A failure has three fields: cause, a readable message from the underlying error, and stage, the boot stage that failed when the cause is a boot cause.
| Cause | What happened | What it means for your app |
|---|---|---|
bundleMissing |
The React content packaged in the artifact was not found. | A packaging problem. A retry cannot help. Show the fallback and report it to the React team. |
fingerprintMismatch |
The React content and the native binary in the artifact were not built together. | A packaging problem. A retry cannot help. Ask the React team for a new build of the artifact. |
evaluationError |
The React code threw an error while it loaded, or the runtime could not start. | No surface can open until this is fixed. A retry starts a new runtime, so one or two tries are reasonable. |
surfaceNotRegistered |
The React project has no surface registered under this name. | Only this surface fails. A retry uses the same runtime. If it fails again, report it to the React team. |
renderException |
The surface’s React code threw while rendering, before or after it went live. |
Only this surface fails. Others keep working. A retry mounts it again in the same runtime and can succeed if the error depended on data. |
duplicateSurfaceId |
Another host already shows a surface with the same descriptor id. Only the second host fails. | A bug in your code: one descriptor was given to two hosts. A retry works once the first host is closed. |
- Boot causes fail every waiting surface.
bundleMissing,fingerprintMismatchandevaluationErrorare boot causes: the runtime itself did not start, so every surface that wasmountingfails with the same cause. Surfaces that are alreadyliveare not affected.failure.cause.isBootCausetells you which kind you have. - For logs and analytics, each cause has a stable string:
stringValueon iOS andserializedon Android. The values arebundle-missing,fingerprint-mismatch,evaluation-error,surface-not-registered,render-exceptionandduplicate-surface-id.