If you build the same app for iOS and Android, you end up solving every state problem twice. SwiftUI and Jetpack Compose share the same core idea: UI is a function of state. Most patterns therefore translate almost one to one. The trouble comes from the few places where they do not, because the code looks similar enough that you assume it behaves the same.

This post maps the five patterns that cover most screens in a small app, with the equivalent code on each side and the differences to watch for. The Swift examples assume the Observation framework (iOS 17 and later). The Kotlin examples assume a recent Compose with the lifecycle-runtime-compose artifact.

1. Local state: @State and remember

Local state is owned by one view and nobody else cares about it: a toggle, a counter, whether a section is expanded.

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        Button("Taps: \(count)") { count += 1 }
    }
}
@Composable
fun Counter() {
    var count by rememberSaveable { mutableIntStateOf(0) }

    Button(onClick = { count++ }) {
        Text("Taps: $count")
    }
}

Where they differ: plain remember loses its value when the Activity is recreated, which by default includes rotation, a theme change or a locale change. rememberSaveable survives that, and also survives process death, as long as the value can go in a Bundle. SwiftUI's @State lives as long as the view keeps its identity in the hierarchy, and rotation does not destroy it. It does not survive the process being killed. If you need that, use @SceneStorage for small values.

On Android, use rememberSaveable for anything the user typed or chose. Keep plain remember for things that are cheap to recreate, such as animation state or a cached formatter.

2. Passing state down: @Binding and state hoisting

A child view needs to read and write a value that the parent owns. SwiftUI packages the read and the write into one object. Compose keeps them as two separate parameters.

struct NameField: View {
    @Binding var name: String

    var body: some View {
        TextField("Name", text: $name)
    }
}

// Parent
NameField(name: $profileName)
@Composable
fun NameField(name: String, onNameChange: (String) -> Unit) {
    TextField(
        value = name,
        onValueChange = onNameChange,
        label = { Text("Name") }
    )
}

// Parent
NameField(name = profileName, onNameChange = { profileName = it })

Where they differ: the Compose version is more verbose, but the write path is an ordinary function. The parent can validate, trim or reject the new value before storing it. With a binding, the child writes directly. If you want the same interception point in SwiftUI, pass a value and a closure instead of a binding, or build a custom Binding(get:set:). For form fields with validation, the value-plus-closure shape is often cleaner on both platforms, and it keeps the two codebases structurally aligned.

3. Screen state: @Observable models and ViewModels

Once state involves loading, errors or anything that outlives a single view, it moves into a class.

@Observable
final class NotesModel {
    var notes: [Note] = []
    var isLoading = false

    func load() async {
        isLoading = true
        notes = await NotesRepository.shared.fetch()
        isLoading = false
    }
}

struct NotesScreen: View {
    @State private var model = NotesModel()

    var body: some View {
        List(model.notes) { note in
            Text(note.title)
        }
        .task { await model.load() }
    }
}
data class NotesUiState(
    val notes: List<Note> = emptyList(),
    val isLoading: Boolean = false
)

class NotesViewModel(private val repo: NotesRepository) : ViewModel() {
    private val _state = MutableStateFlow(NotesUiState())
    val state: StateFlow<NotesUiState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            _state.update { it.copy(isLoading = true) }
            val notes = repo.fetch()
            _state.update { it.copy(notes = notes, isLoading = false) }
        }
    }
}

@Composable
fun NotesScreen(vm: NotesViewModel) {
    val state by vm.state.collectAsStateWithLifecycle()

    LazyColumn {
        items(state.notes, key = { it.id }) { note ->
            Text(note.title)
        }
    }
}

Where they differ:

  • Granularity. With @Observable, SwiftUI tracks which properties each view's body actually reads, and only those views update. The Compose example exposes one immutable state object, so every reader sees every change. Compose then skips the composables whose inputs did not change. The single-state-object style is easier to reason about and to test. The per-property style needs less ceremony.
  • Lifetime. An Android ViewModel survives configuration changes and is scoped to a navigation entry or Activity. A SwiftUI model held in @State lives as long as the owning view's identity does. If you create the model in a view that gets rebuilt with a new identity, for example inside a conditional branch, you get a fresh model.
  • Where loading starts. The Swift example loads from .task, which runs again each time the view appears. The Kotlin example loads once in init. Neither is wrong, but decide deliberately. Otherwise a screen can refetch on every tab switch on one platform and never refresh on the other.

Use collectAsStateWithLifecycle() rather than collectAsState() so collection stops while the app is in the background.

4. Side effects: .task(id:) and LaunchedEffect

This is the closest match of the five. Both run async work tied to the view's presence, cancel it when the view leaves, and restart it when a key changes.

.task(id: query) {
    try? await Task.sleep(for: .milliseconds(300))
    guard !Task.isCancelled else { return }
    results = await search(query)
}
LaunchedEffect(query) {
    delay(300)
    results = search(query)
}

Both snippets give you a debounced search. Each keystroke changes the key, which cancels the previous run before it reaches the network call.

Where they differ: cancellation. In Kotlin, delay throws on cancellation, so the block simply stops. In Swift, cancellation is cooperative. With try? swallowing the sleep's error, execution continues unless you check Task.isCancelled, as above. If you forget the check, every keystroke fires a search after a delay.

On both platforms, a wrong key is the usual bug. A key that changes too often restarts work constantly. A constant key, such as LaunchedEffect(Unit) or a plain .task, captures stale values.

5. List identity: Identifiable and key

Both frameworks need a stable identity per row to preserve row state, animate moves and avoid redundant work.

  • SwiftUI: conform the model to Identifiable, or pass id: to ForEach. You cannot omit the identity, but you can pick a bad one, such as id: \.self on values that are not unique, or an array index.
  • Compose: items(list, key = { it.id }). The key is optional, and the default is position. This is why the bug is more common on Android. Without a key, deleting the first row makes every row below it inherit the state of its predecessor.

In both cases the id should come from your data, not from position and not from a UUID generated at render time. If the data syncs with a server, decide early which id is canonical. The post on offline-first sync covers client-generated ids, which also work well as list keys.

How to check that updates are not excessive

Do not guess whether a screen is doing too much work. Measure it.

  • SwiftUI: temporarily add let _ = Self._printChanges() at the top of a body to log what triggered each evaluation. Use the SwiftUI template in Instruments for a fuller picture.
  • Compose: the Layout Inspector in Android Studio shows recomposition and skip counts per composable. A count that climbs while nothing visible changes is the thing to investigate.

Check in a release build before optimising. Debug builds on both platforms are considerably slower than what users get.

A short checklist for porting a screen

  1. List each piece of state on the screen and mark its owner: the view, the parent or the screen model.
  2. For view-owned state on Android, decide remember or rememberSaveable. Rotate the device and change the system theme to verify.
  3. Check where loading is triggered and confirm both platforms refetch under the same conditions.
  4. For every effect, write down its key and what should happen when the key changes mid-flight.
  5. Give every list a stable key from the data.
  6. Test process death on Android: background the app, kill the process from Android Studio or with adb shell am kill, then return to it.

State is also where accessibility regressions tend to creep in, for instance a custom toggle that updates visually but never announces its new value. The earlier post on accessibility basics in SwiftUI and Compose is a good companion check.

Conclusion

The patterns map closely: @State to remember, @Binding to hoisted value and callback, @Observable models to ViewModels, .task(id:) to LaunchedEffect, and Identifiable to key. Most cross-platform bugs come from the differences underneath: Activity recreation, model lifetime, cooperative cancellation and optional list keys. If you keep the same ownership structure on both sides and verify those four differences explicitly for each screen, the second implementation is mostly a matter of translating syntax.