Basics
What this part of the system is, what it is responsible for, and the vocabulary you need before the mechanics.
1.1Definition
The one-paragraph summary, then where its responsibility starts and stops.
Front ends in data-heavy apps own far more than pixels: what the user sees, each screen's state machine, perceived speed, offline behaviour, real-time updates, streaming AI and accessibility. Strong answers describe these layers as precisely as the backend.
- Render immutable UI state derived from a local source of truth
- Model each screen as a small state machine with explicit loading, empty, error, offline and pending states
- Own perceived performance: startup, scrolling, image and video memory
- Handle offline, retries and conflicts visibly and honestly
- Integrate real-time sockets and streaming AI responses smoothly
- Meet accessibility and localisation requirements by default
- Call the network from views or composables
- Keep business rules in UI code
- Block the main thread with parsing, hashing or database work
- Hide failures behind infinite spinners
- Encode meaning with colour alone
1.2Patterns and terms
The words used in the rest of this page.
| Term | Meaning |
|---|---|
| Loading / empty / content / error | The four base states every list screen must design. |
| Pending / synced / conflict / failed | Per-row sync states for offline-first data. |
| Optimistic update | Show the change immediately and reconcile when the server answers. |
| Skeleton | Placeholder shapes that match final layout, used only on first load. |
| Stale-while-revalidate | Show cached data, refresh in the background, update in place. |
| Idempotent intents | A double tap produces the same result as a single tap. |
1.3Key concepts
Ideas this deep dive relies on, in one sentence each.
Table of pending local writes, committed in the same transaction as the data, drained by the sync engine.
Android library for deferrable, guaranteed background work.
1.4One screen, end to end
A concrete example first, so the mechanics have something to attach to.
Take the job detail screen in the inspection app. When it opens, the ViewModel subscribes to a database query for the job, its answers and its media. The first frame renders from SQLite in about 50 ms, before any network activity.
The technician changes an answer. The ViewModel sends an intent to the repository, which writes the answer and an outbox row in one transaction. The query emits again, the reducer produces a new immutable state with that field marked pending, and Compose recomposes only that row.
In the background, the sync engine pushes the change and the server returns the supervisor’s edit to the instructions. The same query emits again; the instructions update in place and a small ‘Updated by Priya’ label fades in. No screen code knows the network exists.
If the push returns a conflict, the row’s state becomes conflict, the reducer maps it to an amber badge, and tapping it navigates to the resolver. The team designed, named and screenshot-tested every one of these states before the feature shipped.
Question
Know what you are reading for. These are the questions this deep dive prepares you to answer, and the rounds where they come up.
2.1Target questions
Keep them in mind while you read the detail.
- How do you structure a screen in an offline-first app?
- How do you make a list of 10,000 items smooth on a cheap phone?
- How do you design for failure in the UI?
- What changes in the front end when you add AI?
Model answers are in part 4, after the detail that supports them.
2.2Interview rounds
System design rounds where this component is part of a strong answer.
Detailed answer
How it actually works: the components, the states it moves through, a full run, and the code.
3.1Client architecture
The parts and how they connect.
- Unidirectional data flow
- Views send intents; a ViewModel or store reduces intents and data changes into one immutable state object; views render it. This is MVI on Android, the same shape with @Observable models or TCA on iOS, and a Zustand or Redux store in React.
- Observe, don’t fetch
- Screens subscribe to database queries. Network results go into the database, which updates the screen. That gives offline support, instant reopening and one source of truth.
- Effects
- One-off events such as navigation, toasts and haptics are separate from state, so rotating the device or recomposing does not repeat them.
- Real-time and streaming
- Sockets and server-sent events are data sources like any other: they write to the database (chat) or to a stream buffer (AI tokens) that the reducer consumes.
- Design system
- Tokens and components with accessibility built in. Screens compose components; they don’t restyle them.
3.2A user action through the layers
One run, step by step.
- The view never waits for the network; the user sees their change in the same frame.
- The same observation path delivers local edits, sync results and real-time updates, so you test one code path.
3.3Code
Working code for the core of it.
MVI ViewModel with a reducer (Kotlin, Compose)
1data class JobUi(val title: String = "", val fields: List<FieldUi> = emptyList(),2 val banner: Banner? = null, val loading: Boolean = true)3 4sealed interface JobIntent { data class SetAnswer(val fieldId: String, val value: String) : JobIntent; data object Retry : JobIntent }5 6class JobViewModel(private val jobId: String, private val repo: JobRepo, net: NetworkMonitor) : ViewModel() {7 val ui: StateFlow<JobUi> = combine(repo.observeJob(jobId), repo.observeFields(jobId), net.online, repo.pendingCount()) { job, fields, online, pending ->8 JobUi(9 title = job.title,10 fields = fields.map { it.toUi() }, // each carries its sync badge11 banner = when { !online && pending > 0 -> Banner.Offline(pending); fields.any { it.conflict } -> Banner.NeedsReview; else -> null },12 loading = false,13 )14 }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), JobUi())15 16 fun onIntent(i: JobIntent) = viewModelScope.launch {17 when (i) {18 is JobIntent.SetAnswer -> repo.setAnswer(jobId, i.fieldId, i.value) // row + outbox, returns fast19 JobIntent.Retry -> repo.retryFailed(jobId)20 }21 }22}The same state in a Compose screen (Kotlin)
1@Composable2fun JobScreen(vm: JobViewModel) {3 val ui by vm.ui.collectAsStateWithLifecycle() // stops collecting in the background4 Scaffold(topBar = { TopAppBar(title = { Text(ui.title) }) }) { pad ->5 LazyColumn(contentPadding = pad) {6 ui.banner?.let { b ->7 item(key = "banner") { BannerRow(b, onRetry = { vm.onIntent(JobIntent.Retry) }) }8 }9 items(ui.fields, key = { it.id }) { field -> // stable keys: rows keep their state10 FieldRow(field, onChange = { v -> vm.onIntent(JobIntent.SetAnswer(field.id, v)) })11 }12 }13 if (ui.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(pad))14 }15}React web dashboard: cached queries plus live invalidation
1function useJobs(region: string) {2 const qc = useQueryClient();3 const jobs = useQuery({ queryKey: ['jobs', region], queryFn: () => api.jobs(region), staleTime: 30_000 });4 useEffect(() => {5 const ws = new WebSocket(WS_URL + '?region=' + region);6 ws.onmessage = e => {7 const change = JSON.parse(e.data);8 qc.setQueryData(['jobs', region], (old: Job[] | undefined) => upsert(old ?? [], change.job)); // patch in place9 };10 return () => ws.close();11 }, [region, qc]);12 return jobs;13}3.4Tested code, explained
A working implementation, then what each part does and why.
Every state a row can show
Name the states before you build the screen. The compiler then makes sure no screen forgets one.
1/** Everything one row can show. The compiler makes every screen handle all of them. */2sealed interface RowUi {3 data object Synced : RowUi4 data object Pending : RowUi5 data class Conflict(val mine: String, val theirs: Theirs) : RowUi6 data class Failed(val reason: String) : RowUi7}8 9/** A pure function: the same row always draws the same way, so it needs no network to test. */10fun rowUi(job: Job): RowUi = when (job.syncState) {11 SyncState.SYNCED -> RowUi.Synced12 SyncState.PENDING -> RowUi.Pending13 SyncState.CONFLICT -> {14 val theirs = checkNotNull(job.theirs)15 RowUi.Conflict(job.answers[theirs.field].orEmpty(), theirs)16 }17 SyncState.FAILED -> RowUi.Failed(job.error ?: "Could not save")18}sealed interface RowUi- A closed list. Adding a state breaks the build wherever it isn't handled.
fun rowUi(job: Job)- A pure function, with no network or clock involved, so a test needs only a row.
RowUi.Conflict(job.answers...- Carries both values, so the resolver screen has what it needs.
Compiled and tested by npm run test:mobile.
A screen as one mapping
The whole list is a transformation of one database query. That's why the screen needs no sync logic.
1data class JobRow(val id: String, val ui: RowUi)2data class ListSummary(val rows: List<JobRow>, val ticks: Int, val needsReview: Int)3 4/** The whole screen is one mapping over the database query. It never mentions the network. */5fun jobList(db: LocalDb): Flow<ListSummary> = db.jobs6 .map { jobs ->7 val rows = jobs.values.sortedBy { it.id }.map { JobRow(it.id, rowUi(it)) }8 ListSummary(rows, rows.count { it.ui is RowUi.Synced }, rows.count { it.ui is RowUi.Conflict })9 }10 .distinctUntilChanged()db.jobs.map { ... }- Each commit produces one new screen state, whoever made the change.
distinctUntilChanged()- If a sync changed nothing visible, nothing redraws.
val ticks: Int- The eleven green ticks and one amber badge are simply counts of this list.
Compiled and tested by npm run test:mobile.
Redrawing only what changed
140 pulled changes may touch three rows on screen. Compose and RecyclerView do this for you, and this is the idea underneath.
1/** Which rows must redraw. 140 pulled changes may touch only a few rows on screen. */2fun changedRows(old: List<JobRow>, new: List<JobRow>): Set<String> {3 val before = old.associateBy { it.id }4 return new.filter { before[it.id] != it }.map { it.id }.toSet()5}old.associateBy { it.id }- Looks up each row's previous state in constant time.
before[it.id] != it- Data classes compare by value, so an unchanged row doesn't redraw.
Compiled and tested by npm run test:mobile.
3.5Per-platform toolkit
Android
- Jetpack Compose, ViewModel + StateFlow, Hilt, Room with Flow, Paging 3.
- Coil for images, Media3 for video, WorkManager for background work.
- Baseline Profiles and Macrobenchmark for startup and scroll; JankStats in production.
- Paparazzi or Roborazzi screenshot tests; Maestro for end-to-end flows.
iOS
- SwiftUI with @Observable models or TCA; UIKit collection views for very heavy lists.
- GRDB ValueObservation or SwiftData @Query for reactive data.
- Nuke or Kingfisher for images; AVFoundation for media.
- Instruments and MetricKit for performance; swift-snapshot-testing and XCUITest.
React Native
- New Architecture (Fabric, Turbo Modules, JSI) with Hermes.
- FlashList for lists, expo-image or FastImage, Reanimated for animations on the UI thread.
- WatermelonDB or op-sqlite for reactive local data; Zustand or Redux Toolkit for UI state.
- Flashlight and the Hermes profiler; Detox or Maestro for flows.
Web dashboards
- React with TypeScript, TanStack Query for server state, WebSockets or SSE for live updates.
- Virtualised tables for large lists; charts with accessible data tables.
- Playwright for end-to-end tests; Storybook with visual regression for components.
Q&A
The questions from part 2, now with model answers. Try each one out loud before opening it.
4.1Front-end interview questions
How do you structure a screen in an offline-first app?
How do you make a list of 10,000 items smooth on a cheap phone?
How do you design for failure in the UI?
What changes in the front end when you add AI?
Extra depth
Practical context for real projects: which technology to pick, what successful teams do, what to measure and the edge cases to plan for.
5.1Choices and when to pick them
Show detailsHide details
| Need | Options | When to pick |
|---|---|---|
| State management | MVI/UDF · TCA · Zustand · Redux Toolkit · TanStack Query | UDF everywhere; TanStack Query for server state on the web; a store for cross-screen UI state. |
| Local reactive data | Room · GRDB · SwiftData · WatermelonDB · op-sqlite | Whatever gives observable queries on SQLite on your platform. |
| Lists | LazyColumn · UICollectionView · FlashList · virtualised tables | Stable keys, content types, fixed or estimated sizes. |
| Images and media | Coil · Nuke · Kingfisher · expo-image · Media3 · AVPlayer | Request sized images; one active video player. |
| Testing | Screenshot tests · Maestro · Detox · XCUITest · Playwright | Screenshots for every state; a few end-to-end flows for critical paths. |
| Feature delivery | Feature flags · server-driven UI · OTA for JS (EAS Update) | Flags for every risky change; SDUI only for content screens. |
5.2Front-end metrics
Show detailsHide details
| Metric | Why it matters |
|---|---|
| Cold start to first meaningful content (p50, p90 by device class) | The first impression; set a budget per tier. |
| Dropped or slow frames during scroll | Smoothness on real devices, not flagships. |
| Time from tap to visible change | Should be one frame for local writes. |
| Crash-free and ANR-free sessions | Release gates. |
| Share of screens shown from cache | Shows offline-first actually working. |
| Accessibility issues found in CI | Keeps the bar from slipping. |
5.3Hard cases
Show detailsHide details
| Case | How it is handled |
|---|---|
| Process death mid-flow | Persist screen state with SavedStateHandle or SceneStorage; reload from the database on return. |
| Configuration change repeats a toast or navigation | Model one-off effects separately from state. |
| List jumps when data updates | Stable keys, reserved image sizes, and insert-above only on user request. |
| Thousands of rows update at once during sync | Batch database writes per page so observers emit once. |
| Streaming text causes jank | Buffer tokens and render in 50 ms batches; re-parse only the last paragraph. |
| Right-to-left and large fonts break layouts | Screenshot tests in those variants; avoid fixed heights for text. |