Cross-platform interview questions
72 questions from the Cross-platform lessons. Open a question to see the junior, mid and senior answers. Each one links to the lesson that explains it.
Choosing
Why did you choose this framework for the project?
- Junior
- I chose it because the team already knew it and it met the product requirements. It was the path of least resistance for our timeline.
- Mid
- I evaluated four options against team skills, code-sharing needs, and platform-API depth. I built a weighted matrix and the chosen option scored highest. The main trade-off I accepted was a larger app size in exchange for sharing most of the UI code.
- Senior
- Beyond the matrix, I checked whether the rendering model matched our animation and list-performance needs. Flutter draws every frame itself on its own UI and raster threads, while Compose renders through Android's UI toolkit and RenderThread, and React Native renders native views driven from JavaScript. I verified the choice by profiling a prototype of our heaviest screen on our lowest supported device with Perfetto (and Flutter DevTools or the React Native profiler where relevant) and confirmed the frame-time budget was met before committing.
How would you migrate an existing native Android app to KMP?
- Junior
- I would create a new KMP module and move shared code like networking and data into commonMain, keeping the Android UI in Compose.
- Mid
- I would add a shared Gradle module, keep the Android UI native, and migrate one feature's data layer at a time. The usual pitfall is an Android-only dependency that blocks sharing; I would audit the dependency graph first and hide those calls behind interfaces implemented per platform.
- Senior
- I would start by measuring how much logic actually moves to commonMain, because the number is often lower than expected. I would set up CI on a macOS runner early so iOS targets compile on every commit, keep the Android app shippable at every step, and define a clear exit criterion: if only a small fraction of the code is shared, the extra build and tooling cost is not justified and I would keep the app native.
What are the performance trade-offs of Flutter versus native Compose on Android?
- Junior
- Flutter draws its own UI with Impeller, while Compose uses Android's own UI toolkit. Both can run smoothly, but Flutter adds its own engine to the app.
- Mid
- Impeller precompiles its shaders, which removes the runtime shader-compilation jank Flutter had with Skia. Flutter still ships its engine and compiled Dart code, so app size and baseline memory are usually higher than a pure Compose app. Compose renders through the platform's Choreographer and RenderThread, so there is no second engine.
- Senior
- In an add-to-app scenario each FlutterEngine has its own memory cost and startup time, so I would pre-warm and cache one engine instead of creating one per screen. I would profile with Perfetto and Flutter DevTools on the target device, compare frame times for our specific animation and list workloads, and check whether the extra memory footprint is acceptable on the minimum supported hardware.
How does React Native's New Architecture change the integration story?
- Junior
- The old bridge passed asynchronous, batched JSON messages between JavaScript and native code. The New Architecture uses JSI, so JavaScript can hold references to C++ objects and call them directly.
- Mid
- Fabric is the new renderer and supports React's concurrent features and synchronous layout, and Turbo Modules are loaded lazily when first used instead of all at startup. In a brownfield app, the Application provides a ReactHost and screens live in a ReactActivity or ReactFragment. Check that the native libraries you depend on support the New Architecture; an interop layer covers many older modules, but not all.
- Senior
- In a brownfield integration, the main risk is lifecycle: the ReactHost is shared across screens, so I would create it once in the Application, make sure React screens are torn down cleanly when the host Activity finishes, and test back navigation between native and React screens. I would check that no Turbo Module does heavy work on the main thread during initialization, and add a test that opens and closes the React screen repeatedly while watching memory in the Android Studio profiler.
Kotlin Multiplatform
What is Kotlin Multiplatform and when would you choose it over a native-only approach?
- Junior
- Kotlin Multiplatform lets you write shared Kotlin code that compiles for both Android and iOS. You choose it when the business logic, networking, and data layers are the same on both platforms and you want to avoid maintaining them twice.
- Mid
- KMP compiles commonMain to JVM bytecode for Android and to native code with Kotlin/Native for iOS. The main pitfall is over-sharing: platform-specific UI or OS APIs stay in androidMain or iosMain behind interfaces. A good default is to share logic and data, and to treat shared UI with Compose Multiplatform as a separate decision.
- Senior
- The real trade-off is build and tooling complexity versus duplication cost. KMP adds Kotlin/Native builds that need a Mac, slower iOS compile times, and a Swift interop layer someone must own. I verify the decision by measuring how much logic is truly identical across platforms and by checking that the iOS developers are on board, because a shared module they cannot debug becomes a bottleneck.
Explain how KMP source sets and the default hierarchy template work.
- Junior
- commonMain is at the top and is shared by all targets. androidMain is for Android, and iosMain is the parent of the iOS target source sets like iosArm64Main and iosSimulatorArm64Main. Code in a parent source set is visible to its children.
- Mid
- Each declared target gets its own source set. The default hierarchy template groups them into intermediate source sets: iOS targets share iosMain, Apple targets share appleMain, and all Kotlin/Native targets share nativeMain. You put shared iOS code in iosMain and only truly target-specific code in a leaf. If you add manual dependsOn calls, the template is no longer applied automatically; call applyDefaultHierarchyTemplate() explicitly to keep it.
- Senior
- When the default shape does not fit, I call applyDefaultHierarchyTemplate() explicitly and add only the extra intermediate source set with dependsOn, or define a custom tree with applyHierarchyTemplate { }, instead of rebuilding the whole hierarchy by hand. An intermediate source set only makes sense when the targets it groups share APIs, so I group by platform capability, never by screen size or product flavour. I guard the structure by compiling every target in CI and by keeping commonMain free of platform imports.
When should you use expect/actual versus an interface with dependency injection?
- Junior
- Use expect/actual for small platform primitives, like a function that returns the platform name. Use an interface with DI when the platform difference is a whole component, like a logger or a storage backend.
- Mid
- expect/actual is checked by the compiler: every target must provide an actual, so a missing one is a build error. An interface is ordinary Kotlin: you implement it per platform, inject it, and swap in a fake in commonTest. The pitfall with expect/actual is that each new declaration needs an actual in every platform source set, and expect/actual classes are still Beta.
- Senior
- I default to interfaces plus DI, which is also what the Kotlin docs recommend wherever standard constructs work, and keep expect/actual for low-level primitives such as a UUID or a platform logger function, or for a factory that builds the platform implementation. I avoid expect/actual classes in production while they are Beta. When reviewing, I check that expect declarations stay small and do not leak into the public API of shared modules.
How does Kotlin/Native interop with Swift work, and what are the limitations?
- Junior
- Kotlin/Native compiles the shared code into a .framework that Xcode links. It generates an Objective-C header that Swift imports, so Swift can call Kotlin classes and functions.
- Mid
- Because interop goes through Objective-C, some Kotlin features lose detail: suspend functions become completion handlers that Swift can call with async, generics on interfaces are erased, sealed classes become plain class hierarchies, and Flow is not an AsyncSequence. Tools like SKIE or KMP-NativeCoroutines fix the Flow and sealed-class experience. Direct Swift export, which skips Objective-C, is still experimental.
- Senior
- I design the exported API for Swift on purpose: a small facade with simple types, no leaking of internal classes, and @ObjCName (an opt-in experimental annotation) where generated names are awkward. I verify it by building the framework with ./gradlew linkDebugFrameworkIosSimulatorArm64, reading the generated header, and running Swift tests that call the exported API, so signature changes from a Kotlin or library upgrade show up in CI instead of in the iOS team's build.
What is expect/actual and when would you use it?
- Junior
- expect/actual lets you declare a function or property in commonMain and provide platform-specific implementations in androidMain, iosMain and other platform source sets. You use it for platform primitives like getting the OS name or generating a UUID.
- Mid
- The expect declaration defines the contract; each actual must be in the same package and match the signature. Functions and properties are stable, but classes are still Beta and produce a warning unless you pass -Xexpect-actual-classes. The usual pitfall is reaching for expect/actual when an interface injected with DI would be simpler and easy to fake in commonTest.
- Senior
- In a real codebase I keep expect/actual to a handful of small primitives, and sometimes an expect factory function that builds the platform implementation of an interface. Everything else goes through interfaces injected by DI, which is also what the Kotlin docs recommend. I check coverage by compiling every target in CI, and I make sure expect declarations do not leak into the public API that other modules or Swift consume.
How do KMP source sets work?
- Junior
- commonMain is shared by all targets. androidMain is for Android and iosMain is for iOS. Code in commonMain can call expect declarations, and the platform source sets provide the actual implementations.
- Mid
- The default hierarchy template in Kotlin 1.9.20+ creates intermediate source sets automatically. iosMain is the parent of iosArm64Main and iosSimulatorArm64Main, and sits under appleMain and nativeMain. Shared iOS code goes in iosMain and only device- or simulator-specific code goes in a leaf. Each source set can have its own dependencies.
- Senior
- I lean on the default template and only extend it: call applyDefaultHierarchyTemplate() explicitly and add an extra intermediate source set with dependsOn, for example one shared by JVM and Android, or define a custom tree with applyHierarchyTemplate { }. An intermediate source set only works when its targets share APIs. I keep commonMain free of platform imports and compile every target in CI as a merge gate.
expect/actual versus interface plus DI: which do you choose and why?
- Junior
- Both let you supply platform implementations. expect/actual is checked by the compiler for every target; an interface is plain Kotlin that you implement per platform and pass in.
- Mid
- expect/actual gives compile-time completeness: the build fails if a target has no actual, but there is exactly one actual per target, so tests cannot swap it. An interface plus Koin lets you inject different implementations, including fakes in commonTest. expect/actual classes are also still Beta.
- Senior
- I use expect/actual for a few primitives and interfaces for everything else. Interfaces keep commonMain independent of how many targets exist, support multiple implementations per platform, and make testing easy; expect/actual is best when the implementation is tiny and there is genuinely one per platform. I verify the split by keeping commonMain free of platform imports and running a full multi-target build in CI.
What happens when you add a new target like iosSimulatorArm64()?
- Junior
- You add the target in the kotlin { } block of the Gradle file. Gradle creates a source set for it, and every expect declaration needs an actual that covers the new target.
- Mid
- With the default hierarchy template, iosSimulatorArm64Main is created under iosMain. If your iOS actuals already live in iosMain, the new target inherits them and builds. If they live in another leaf, the new target fails with missing-actual errors. To get a framework for the simulator, you also declare binaries.framework for that target.
- Senior
- I add the target, run a full build of all targets, and fix missing actuals by moving them up to iosMain rather than copying them into the new leaf. I check that every library dependency publishes artifacts for the new target, because a dependency without it fails resolution. I also confirm the simulator framework is produced and that the Xcode build picks the right one, and I make the all-targets build a CI merge gate.
How do you structure a shared networking layer in Kotlin Multiplatform?
- Junior
- You put the API models and the Ktor client logic in commonMain. The platform-specific part is the HTTP engine: OkHttp on Android and Darwin on iOS. You wire it with a multiplatform DI approach such as Koin because Hilt is Android-only.
- Mid
- The engine is the only expect/actual boundary. You declare expect fun createEngine(): HttpClientEngine in commonMain and return OkHttp.create() and Darwin.create() from the platform source sets. The HttpClient factory, ContentNegotiation with one shared Json instance, HttpTimeout, and logging all live in commonMain. The compiler links each target to its actual, so there is no platform branch.
- Senior
- I keep configuration out of engine-specific blocks, because Darwin and OkHttp support different features: for example, Darwin has no connect timeout. Shared behaviour goes through Ktor plugins in commonMain, and I run the same integration tests on the Android and iOS simulator targets in CI. The repository is exposed as an interface bound in DI so tests can use a fake or Ktor's MockEngine. For Swift callers I keep suspend functions simple and wrap Flows with SKIE or KMP-NativeCoroutines.
When would you use expect/actual versus an interface with DI in KMP?
- Junior
- Use expect/actual for small platform facts like creating the HTTP engine. Use an interface with DI when the implementation has real logic or you want to swap it in tests.
- Mid
- expect/actual is resolved at compile time: the compiler checks every target has a matching actual, which suits thin, mechanical differences like creating an engine. An interface plus DI is a runtime binding, which suits repositories and platform services you want to fake in tests. expect/actual functions are stable, but expect/actual classes are still Beta, so prefer interfaces for classes.
- Senior
- The trade-off is compile-time guarantees versus flexibility. A missing actual fails the build, while a missing Koin binding only fails when it is resolved at runtime, so I add a Koin verify or startup test that resolves the whole graph for each platform module. I keep expect declarations to small factory functions and push behaviour behind interfaces, so commonTest can run against fakes without any platform code.
How do you handle the database layer across Android and iOS?
- Junior
- With SQLDelight you write .sq files in commonMain, and each platform provides a driver: AndroidSqliteDriver on Android and NativeSqliteDriver on iOS. The generated database code is shared. Room also supports KMP since 2.7.
- Mid
- The driver is the platform piece. On Android it needs a Context, so I create it in an Android DI module and inject an SqlDriver into shared code. Schema changes go in SQLDelight .sqm migration files, and SQLDelight can verify migrations against the stored schema. The database stays the single source of truth: repositories write network results into it and the UI observes queries as Flows.
- Senior
- I choose between SQLDelight and Room by team and needs: SQLDelight if the team likes writing SQL and wants generated code from it, Room if the Android team already knows its DAOs and migrations. Either way I test migrations in CI, run repository tests in commonTest with an in-memory or test driver, and remember that the SQLite version on Android varies by OS version unless a bundled SQLite is used. On iOS I check where the database file lives so backups and app updates behave as expected.
What are the limitations of sharing a Ktor client across platforms?
- Junior
- The engine differs: OkHttp on Android, Darwin on iOS. Some HTTP features behave differently, so you must test on both platforms, and Android-only OkHttp interceptors cannot run in commonMain.
- Mid
- Ktor shares the API, but engine features differ. Darwin supports request and socket timeouts but not a connect timeout, and engine-level settings like OkHttp interceptors or URLSession configuration are platform-specific. To keep behaviour equal I configure timeouts, serialization, and retries with Ktor plugins in commonMain.
- Senior
- Ktor's multiplatform guarantee covers the API surface, not identical behaviour. Things like certificate pinning, proxies, and HTTP/2 handling depend on the engine, so I configure them in each engine block on purpose and document the difference. Shared integration tests run on both targets in CI, and I watch per-platform error rates after release to catch engine-specific failures.
How does Compose Multiplatform render UI on iOS compared to Android?
- Junior
- On Android it uses the normal Jetpack Compose libraries and the Android graphics stack. On iOS it draws the UI itself with Skia through Skiko instead of using UIKit controls. The composable code is the same.
- Mid
- The Compose compiler plugin and runtime are shared; what differs is the platform layer. On Android, Compose Multiplatform resolves to Google's Jetpack Compose artifacts. On iOS, Kotlin/Native compiles the same code to native code and Compose paints into a Metal-backed view with Skia. Because Compose draws its own widgets, fonts, text layout, and scroll physics can differ from Android and from native UIKit, so you test both.
- Senior
- The iOS host is a UIViewController from ComposeUIViewController that renders Compose frames with Skia on Metal, synced to the display refresh. Since nothing is a UIKit view, accessibility and text input go through Compose's own iOS integration, and native views are embedded through UIKit interop composables, which has a cost. In practice I ship the same fonts via Compose resources, review iOS screenshots, test VoiceOver, and profile scrolling on real devices before release.
How do you structure a KMP module that uses Compose Multiplatform?
- Junior
- You put shared composables in commonMain, Android entry code in androidMain, and iOS entry code in iosMain. The Gradle file applies the Kotlin Multiplatform, Compose Multiplatform, and Compose compiler plugins.
- Mid
- In the kotlin block you declare androidTarget(), iosArm64(), and iosSimulatorArm64(). Compose runtime, foundation, and material3 go in commonMain dependencies. The iOS framework is exported with binaries.framework { baseName = "Shared" }. Platform-specific code such as Context or UIViewController stays in its own source set.
- Senior
- The main decision is where the boundary sits. I keep composables, view models, and navigation in commonMain and limit platform source sets to glue: the Activity, the ComposeUIViewController function, and DI modules that bind platform services behind interfaces. Larger apps split shared code into feature modules with one umbrella module that exports the iOS framework, because Swift links one Kotlin framework more easily than several.
What are the main limitations of sharing UI with Compose Multiplatform?
- Junior
- You cannot use Android-only APIs like Context or SharedPreferences in shared code, and Material components look like Material on iOS, not like native iOS controls.
- Mid
- Text and fonts measure differently on iOS, some Android-only libraries are not available in commonMain, and Flow needs a bridge to be used from Swift. Native iOS views such as maps or web views are embedded with UIKit interop, and the Skia runtime adds to the app's binary size.
- Senior
- The trade-off is native feel versus shared code. Navigation transitions, scroll physics, text selection, and accessibility are Compose's implementation, not UIKit's, so an app that must feel fully native on iOS may need SwiftUI for some screens. I decide per screen, keep business logic shared either way, and agree with the iOS team on which screens stay native before committing.
How do you bridge Kotlin coroutines and Flow to Swift in a KMP project?
- Junior
- Suspend functions can already be called from Swift with async. For Flow, you add a library like SKIE or KMP-NativeCoroutines so Swift can loop over it with for await.
- Mid
- Kotlin/Native exports suspend functions as Objective-C completion handlers, which Swift can call with async, but without cancellation propagating back to Kotlin. Flow exports as a plain interface. SKIE, a Gradle plugin from Touchlab, rewrites the Swift API so Flows become AsyncSequences and suspend functions support cancellation. KMP-NativeCoroutines uses a Gradle plugin, @NativeCoroutines annotations, and a Swift package to do the same.
- Senior
- I choose one bridge per project and keep the exported API small: view model state as a StateFlow and a few suspend actions. On the Swift side, collection runs in SwiftUI's .task so it cancels when the view disappears. Swift export, which produces a Swift API directly instead of an Objective-C header, is still experimental, so I would not base a production app on it yet. CI builds the Swift app against the framework so a breaking API change fails before merge.
How does Kotlin/Native expose shared code to Swift?
- Junior
- Kotlin/Native compiles the shared module into an Apple framework and generates an Objective-C header. Swift imports the framework and calls the Kotlin classes and functions like Objective-C APIs.
- Mid
- The header is generated from the public declarations of the shared module for each iOS target. Suspend functions become methods with a completion handler, data classes become Swift classes, nullable types become optionals, and top-level functions are exported on a class named after the file. The framework reaches Xcode through direct integration (a Gradle task in an Xcode build phase), CocoaPods or a Swift package wrapping an XCFramework. I read the generated header to check what Swift actually sees.
- Senior
- Because everything goes through Objective-C, some Kotlin features degrade: generics are lost on interfaces, sealed classes are not exhaustive in Swift, default arguments disappear, and exceptions only propagate when declared with @Throws. So I treat the Swift-facing surface as a public API: keep it small, design it for Swift, rename with @ObjCName where needed, and diff the generated header in CI to catch breaking changes. SKIE fixes several of these gaps at the cost of another compiler plugin to keep compatible with Kotlin upgrades, and Swift export may remove the Objective-C layer once it is stable.
How do you consume a Kotlin Flow from Swift?
- Junior
- Swift cannot use a Kotlin Flow directly in a nice way, so you add a bridge library. The two main options are SKIE and KMP-NativeCoroutines.
- Mid
- SKIE is a Gradle plugin that turns a Flow into a Swift AsyncSequence, so you loop over it with for await. KMP-NativeCoroutines uses annotations, a Gradle plugin and a Swift package and can expose Flows as async sequences, Combine publishers or RxSwift observables. In both cases the collection runs in a Swift Task, and cancelling that Task cancels the Kotlin collector.
- Senior
- I choose SKIE when the iOS code uses Swift concurrency and the team is happy with a compiler plugin, and KMP-NativeCoroutines when the codebase is Combine-heavy or we want explicit annotations on exported APIs. Either way I tie collection to a lifecycle: SwiftUI's task modifier, or a stored Task cancelled when the screen goes away, and I check with the memory graph that dismissed screens are released. I also remember a StateFlow emits its current value immediately, so the first emission is not a change. Both tools must support the project's Kotlin version, so they are part of the upgrade checklist.
What happens with threads and errors when Swift calls a Kotlin suspend function?
- Junior
- Swift can call it with a completion handler or with try await. You should update the UI on the main thread after the result comes back.
- Mid
- The completion handler receives a result and an error. I do not rely on which thread it returns on; I put the calling code in a @MainActor view model so UI state is updated on the main thread after the await. On the Kotlin side I keep functions main-safe with withContext on an injected dispatcher, like on Android.
- Senior
- Errors are the bigger trap. A suspend function without @Throws only propagates CancellationException; any other exception reaching Swift terminates the app. So every failing API either declares @Throws with the expected exception types or returns a sealed result. Plain async bridging also does not cancel the coroutine when the Swift Task is cancelled, so long operations keep running unless we use SKIE or KMP-NativeCoroutines. I test these paths on the iOS simulator target in CI, not only on the JVM.
How do you set up iOS targets and frameworks in the KMP Gradle build?
- Junior
- You declare iosArm64 for devices and iosSimulatorArm64 for the simulator on Apple Silicon Macs, and give each a binaries.framework block with a baseName. Shared iOS code goes in iosMain.
- Mid
- The default hierarchy template creates iosMain and links the target source sets to it, so I do not wire dependsOn by hand. iosX64 is only for Intel Mac simulators and is being phased out. The framework is dynamic unless isStatic is true; many templates choose a static one. Running linkDebugFrameworkIosArm64 produces the framework and its header under build/bin.
- Senior
- In a multi-module project I usually export one umbrella framework, because each separately exported KMP framework contains its own copy of the Kotlin runtime and their types are not interchangeable in Swift. Modules are added with export() only when Swift needs their API directly. A convention plugin applies the targets and framework settings everywhere, CI links the device and simulator frameworks, and release builds produce an XCFramework when the iOS app consumes a prebuilt binary.
How do you structure a KMP project so business logic is shared but platform code stays isolated?
- Junior
- Interfaces, repositories and use cases go in commonMain, and platform implementations go in androidMain and iosMain. A shared Koin module wires the common classes and a platform module binds the platform implementations. Both are loaded when Koin starts.
- Mid
- commonMain never imports a platform type. For example UserSettings is an interface in commonMain, implemented with SharedPreferences in androidMain and NSUserDefaults in iosMain. A shared initKoin function starts Koin with sharedModule and an expect val platformModule, so each platform always loads the right bindings. Android calls initKoin from Application with androidContext, and Swift calls the exported helper at app start.
- Senior
- I treat the source sets as the architecture boundary: the compiler already prevents platform imports in commonMain, so the real decisions are where the interfaces sit and what Swift sees. I keep expect/actual to a few functions or the platform module and put behaviour behind interfaces so commonTest can use fakes. I start one Koin application per process, use scopes for session state, and run a graph test on both the JVM and the iOS simulator target. Feature modules expose their own Koin modules, and the iOS app consumes one umbrella framework with a small Swift-facing API.
Why can you not use Hilt in KMP shared code, and what do you use instead?
- Junior
- Hilt is Android-only, and shared code also has to compile for iOS. Most KMP projects use Koin, which is a multiplatform library.
- Mid
- Hilt is built on Dagger, which generates Java code for the JVM, and Hilt adds Android components on top. Kotlin/Native has no JVM, so neither can run in commonMain. Koin is written in Kotlin with a module DSL that works on all KMP targets. kotlin-inject is another option, with compile-time generated code through KSP.
- Senior
- The trade-off is when you find wiring errors. Dagger and kotlin-inject check the graph at compile time; plain Koin resolves at runtime, so a missing binding is a crash on first use. I close that gap with a test that resolves the full graph per platform, and Koin's verify on the JVM. Koin Annotations or Koin's compiler plugin can add compile-time checking if the team wants it. Some teams keep Hilt in the Android app module and use Koin or manual wiring only in shared code, but two graphs mean duplicated bindings, so I prefer one approach for shared code.
What is the difference between single and factory in Koin, and when does it matter in KMP?
- Junior
- single creates one instance and returns it every time. factory creates a new instance on every get. Screen objects usually use factory.
- Mid
- single lives as long as the Koin application on both Android and iOS. On Android, Koin's viewModel definitions tie screen state to a ViewModelStoreOwner, but iOS screens that resolve objects directly have no such owner, so a single holding user data stays alive across navigation and even logout. I use factory for screen objects and single only for app-wide, user-independent objects.
- Senior
- For state shared by several screens but not the whole app, such as a session or a checkout flow, I use a Koin scope: scoped definitions created with createScope and released with close at a clear lifecycle event, like logout. Closing it is the platform code's responsibility, so I put that in a shared SessionManager rather than in each screen. I test it by logging in as two users in a row and asserting no data from the first appears. If the project uses Compose Multiplatform, the multiplatform ViewModel and Koin's koin-compose-viewmodel give iOS screens a ViewModel lifetime too.
When would you still use expect/actual instead of an interface plus DI?
- Junior
- For small things that differ per platform, like a platform name or a factory function that creates a database driver or an HTTP engine.
- Mid
- expect/actual is resolved at compile time, so a missing actual fails the build, which is good for small required pieces. Functions and properties are stable, while expect/actual classes are still Beta. For behaviour with logic or that tests need to replace, an interface bound in DI is easier to fake.
- Senior
- I use expect for small, required factories, for example the SQLDelight driver or Koin's platformModule, because the compile-time guarantee is worth having there. Everything with behaviour goes behind an interface so commonTest can run with fakes and I can add a target without touching shared logic. I avoid expect classes because they are Beta and force the whole class shape onto every platform. In review I check that expect declarations stay small and that no platform type appears in a commonMain signature.
Flutter
How does Dart null safety compare to Kotlin null safety?
- Junior
- Both are sound and non-nullable by default. String? means the same in both. Dart's ! is Kotlin's !!, and Dart's ?? is Kotlin's elvis operator ?:. Both have ?. for safe calls.
- Mid
- Flow analysis works the same way: after a null check, a local variable is promoted to the non-nullable type, like a Kotlin smart cast. One difference is that Dart does not promote public fields of another class, because a getter could return a different value each time, so you copy the field into a local first. For deferred initialisation Dart has late, which throws LateInitializationError on an early read; Kotlin has lateinit var, which throws UninitializedPropertyAccessException, and by lazy, which matches late final with an initialiser.
- Senior
- The risks in a real codebase are ! and late, because both move null errors back to runtime. I keep ! out of production paths unless a check right before it makes it safe, and I treat late fields in State classes with suspicion: an async callback can read one before initState has assigned it, or after dispose. In CI I run dart analyze with the recommended lints and treat warnings as failures.
What replaces Kotlin coroutines and Flow in Dart?
- Junior
- Future<T> replaces a suspend function: you mark the function async and await it. Stream<T> replaces Flow<T>: you produce one with async* and yield, and consume it with await for or listen.
- Mid
- The big gap is structured concurrency. A Future is not owned by a scope and cannot be cancelled. If one future passed to Future.wait fails, the others still run. In Flutter you check mounted after each await, cancel StreamSubscriptions in dispose, and use CancelableOperation from package:async when you need to drop a result. Streams are closer to Flow: an async* stream starts on listen, and pausing the subscription pauses the generator.
- Senior
- Dart runs each isolate on one thread with an event loop, so async only interleaves work, it does not parallelise it. CPU-heavy work goes to another isolate with Isolate.run, which is the nearest thing to Dispatchers.Default, except isolates do not share memory: data is copied or transferred between them. I check for jank with DevTools in profile mode. Architecturally, I put cancellation in a state holder with a defined lifetime, such as a Riverpod provider or a Bloc, so it plays the role of viewModelScope.
What are Dart 3 sealed classes and how do they compare with Kotlin's?
- Junior
- A sealed class is an abstract base type whose direct subclasses must be in the same library. You branch on it with a switch, much like Kotlin's when on a sealed class.
- Mid
- Like Kotlin, a switch over a sealed type is checked for exhaustiveness, so a missing subclass is a compile error. The trap is that if-case chains are never checked, and a default or wildcard case turns the check off. Object patterns such as Ok(:final value) test the type and bind fields in one step, like a smart cast.
- Senior
- I treat sealed hierarchies as a contract that the compiler enforces: no catch-all cases in switches over them, so adding a subclass forces every call site to be updated. Dart 3 also has class modifiers: final on the subclasses stops other libraries from extending them, which keeps the hierarchy closed. For larger models I combine sealed classes with records or freezed so each variant gets value equality.
How do you model a Kotlin data class in Dart?
- Junior
- Dart has no data class. You write a class with final fields and a const constructor. For a quick tuple you can use a record such as (int, int).
- Mid
- A plain class uses identity equality, so two instances with the same fields are not equal unless you override == and hashCode. You also write copyWith and toString yourself. Records give field equality for free but have no methods and no class name, so they suit small local values rather than domain models.
- Senior
- In production code I generate the boilerplate with freezed (or a similar build_runner generator) so ==, hashCode, copyWith and toString cannot drift from the fields. Value equality matters in Flutter state management: Riverpod and Bloc both skip updates when the new state equals the old one, so a class without proper == either rebuilds too often or, if you mutate and re-emit the same instance, never rebuilds.
What happens when you call setState in a StatefulWidget?
- Junior
- It tells Flutter that the State changed. Flutter calls build() again on the next frame, and the screen shows the new values.
- Mid
- setState runs the callback synchronously, then marks the element dirty. On the next frame Flutter rebuilds dirty elements: build() returns new child widgets and each existing child element is updated if the new widget has the same runtimeType and key, or replaced if not. Several setState calls in one frame cause one rebuild. The callback must be synchronous; do the async work first, then call setState with the result.
- Senior
- The frame runs build, then layout, then paint. Rebuilding is usually cheap because widgets are small immutable objects; what costs time is rebuilding big subtrees and render objects that then need relayout or repaint. Render objects only mark themselves for layout or paint when a property actually changes, so an identical rebuild does little work further down. To keep rebuilds small, I push state down to the widgets that use it, use const for static parts, and confirm with Track widget builds in the DevTools Performance view in profile mode.
What is the difference between the Widget, Element and RenderObject trees?
- Junior
- Widgets are immutable descriptions of the UI. Elements are the live nodes that hold State and connect widgets to render objects. Render objects do layout, painting and hit-testing.
- Mid
- Widgets are recreated on every build. Elements persist across rebuilds as long as the widget at that position keeps the same type and key, which is why State survives. BuildContext is the element itself, which is why using a context after its widget has left the tree is an error.
- Senior
- The trees are not one-to-one. Every widget has an element, but only RenderObjectElements own a render object; StatelessWidget and StatefulWidget elements only compose other widgets. InheritedWidget elements track their dependents so that Theme.of or a provider lookup rebuilds only the widgets that read it. For debugging I use the DevTools Widget Inspector, or debugDumpApp and debugDumpRenderTree to print the element and render trees.
When do you need a Key in Flutter, and which one?
- Junior
- When list items can be reordered, added or removed and they have state. ValueKey with a unique id is the usual choice.
- Mid
- Without keys, Flutter matches children by position, so after a reorder a State can stay attached to the wrong item. A ValueKey lets Flutter match old and new children by identity. GlobalKey is for the rarer cases where State must move to a different parent or be reached from outside, such as a FormState.
- Senior
- Keys only compare among siblings, apart from GlobalKey, which is unique in the whole app and costs more to manage, so I avoid using it for list identity. Stateless items with no internal state often work without keys, but anything with State, focus, animation or a TextEditingController needs them. A classic bug is using the index as a ValueKey, which gives no stability at all, or UniqueKey created in build, which destroys and recreates the State on every rebuild.
How does const affect performance, and where do you apply it?
- Junior
- const widgets are created once at compile time and reused. Add const to widgets whose arguments never change, like const Text('Hello') or const SizedBox(height: 8).
- Mid
- Identical const expressions are canonicalized to one instance. When Flutter compares the old and new child and finds the same instance, it skips updating that element and its subtree. That saves allocations and build work on every rebuild of the parent.
- Senior
- A widget can only be const if all its arguments are constants, so one dynamic value (a string with interpolation, a theme lookup) stops the parent from being const. I enable the prefer_const_constructors lint in analysis_options.yaml so the analyzer suggests them. const is a cheap win but not a cure: if a large subtree rebuilds because state lives too high, moving the state down matters more. I measure with Track widget builds rather than assuming.
Explain the difference between Provider, Riverpod and Bloc. When would you pick each?
- Junior
- Provider puts an object such as a ChangeNotifier into the widget tree and widgets read it with context.watch or context.read. Riverpod declares providers outside the tree and widgets read them with ref.watch, so it does not depend on BuildContext for lookups. Bloc is event-driven: widgets add events and the bloc emits new states. I would pick Provider for a small app, Riverpod for most new apps where I want testable dependencies, and Bloc when the team wants explicit events.
- Mid
- Provider is a thin layer over InheritedWidget, so lookups depend on where you are in the tree and a provider must sit above every reader, which bites with dialogs and new routes. Riverpod moves the dependency graph out of the widget tree: providers watch other providers through Ref, async state comes as AsyncValue, and tests override providers in a ProviderContainer. Bloc separates input (events) from output (states), which makes behaviour easy to trace and to test with bloc_test, at the cost of more classes. Typical bugs: watch placed too high with Provider, ref.read in build with Riverpod, and mutating state in place with Bloc.
- Senior
- I weigh it on team and codebase more than features. Riverpod gives the best composition and test story for new projects, but its API changed across major versions (StateNotifier is now legacy), so I check that the team follows current guidance. Bloc fits large teams that want strict, reviewable patterns and an audit trail of events through BlocObserver; the boilerplate is the price. Provider is fine for small apps or as plain DI. In an existing codebase I would rather standardise on one and migrate feature by feature than add a fourth pattern, and I measure rebuild scope with DevTools before and after.
How does Provider work under the hood? What is the role of InheritedWidget?
- Junior
- Provider wraps your object in an InheritedWidget placed above the widgets that need it. When a ChangeNotifier calls notifyListeners, the widgets that watched it rebuild.
- Mid
- InheritedWidget is Flutter's way to pass data down the tree. context.watch registers the calling element as a dependent of the provider's inherited element, using dependOnInheritedWidgetOfExactType under the hood. When the notifier changes, Provider tells the inherited element to notify its dependents, and only those elements are marked for rebuild. context.read looks up the element without registering a dependency, which is why it is safe in callbacks.
- Senior
- Because subscriptions are per element, the widget that calls watch decides the rebuild scope, which is why select and Consumer exist. Lookups walk up the tree, so a provider placed inside one route is not visible from a dialog or another route; that is the source of most provider-not-found errors. Provider also handles lifecycle: the create variants dispose what they created, and the value variants do not. Riverpod drops the InheritedWidget lookup for its own container, which is why providers can depend on each other without a BuildContext.
What is the difference between watch and read, in Provider and in Riverpod?
- Junior
- watch subscribes the widget, so it rebuilds when the value changes. read gets the current value once. Use watch in build and read in callbacks like onPressed.
- Mid
- In Provider, watch registers an inherited-widget dependency and read does not; calling watch outside build is an error caught in debug mode. In Riverpod, ref.watch in a widget's build or a provider's build subscribes, and ref.read is a one-off read for event handlers. Using read in build is the classic stale-UI bug.
- Senior
- Inside providers, ref.watch builds the dependency graph: when a watched provider changes, the dependent provider rebuilds, which is how derived state stays consistent. ref.listen is the third option, for side effects such as showing a snackbar when a provider enters an error state. In reviews I look for read in build, watch inside callbacks, and widgets that watch a whole object when select would narrow the rebuild.
How would you unit-test logic that uses Riverpod or Bloc without pumping a widget?
- Junior
- For Riverpod, create a ProviderContainer, override providers with fakes, and read the provider. For Bloc, create the bloc, add events, and check the emitted states.
- Mid
- In Riverpod 3, ProviderContainer.test creates a container that is disposed after the test; I pass overrides such as userRepositoryProvider.overrideWithValue(FakeRepository()) and await container.read(userProvider.future) for an AsyncNotifier. For Bloc, the bloc_test package provides blocTest with build, act and expect, which asserts the exact sequence of emitted states. Forgetting to override a provider that does real network calls is the usual mistake.
- Senior
- I keep side effects behind providers or constructor parameters so tests only replace those, never the notifier or bloc under test. For Riverpod I also test lifecycle with ref.onDispose and auto-dispose providers, and use container.listen to record every state change in order. For Bloc I assert errors with the errors parameter of blocTest and seed a starting state with seed. Widget tests then only cover wiring, so most of the suite stays fast and deterministic.
What is the difference between Navigator push/pop and go_router, and when would you choose one over the other?
- Junior
- Navigator push and pop are imperative: you push a MaterialPageRoute and pop it. go_router is declarative: you list routes with URL paths and navigate by location, like /orders/42. For a few screens without deep links, plain Navigator is fine. For deep links and auth guards, go_router is simpler.
- Mid
- Plain Navigator keeps a stack of Route objects and you change it with push and pop. Supporting deep links that way means route names in onGenerateRoute, or the full Router API with a RouterDelegate and RouteInformationParser, which is a lot of code. go_router is built on the Router API: it matches a location against GoRoute paths, gives you pathParameters, central redirects, and ShellRoute or StatefulShellRoute for tabs. I would choose go_router once the app has deep links, auth gating, or tabs with their own back stacks.
- Senior
- go_router puts the whole route tree in one place, which makes deep links testable but can grow large, so I split route lists per feature and compose them. I design the tree so that go builds sensible back stacks: detail routes are nested under their list so a cold-start deep link still has a parent. Auth lives in one redirect driven by a refreshListenable, with an explicit restoring state so the redirect never decides before the session is loaded. I check behaviour with integration tests that launch with a deep link and assert the visible screen, and with a NavigatorObserver that logs the stack in debug builds.
How do you handle the Android back button in Flutter now that WillPopScope is deprecated?
- Junior
- You wrap the screen in PopScope. Setting canPop to false blocks the back gesture, and onPopInvokedWithResult tells you a pop was attempted so you can show a dialog.
- Mid
- PopScope replaces WillPopScope. The old widget answered asynchronously whether a pop was allowed, which does not work with Android's predictive back, where the system must know before the gesture starts. With PopScope you declare canPop up front. onPopInvokedWithResult runs both when the pop happened (didPop true) and when it was blocked (didPop false), so I check the flag and only show the confirmation dialog when didPop is false, then pop manually if the user confirms.
- Senior
- PopScope guards back gestures and maybePop, not every way a route can leave. A direct Navigator.pop or a go_router navigation that rebuilds the stack bypasses it. When leaving must always be confirmed, for example an unsaved form, I use GoRoute's onExit, which runs when go_router removes the route, and keep PopScope for the system gesture. On Android I opt in to predictive back with android:enableOnBackInvokedCallback in the manifest and test the back animation on a recent Android version, because canPop must reflect the real state at the moment the gesture begins.
A user taps a deep link to /orders/42 on a cold start and lands on the wrong screen. How do you debug this?
- Junior
- I check that AndroidManifest.xml has an intent filter on MainActivity with the right scheme, host, and path, and that a route matching /orders/:id exists in the router. Then I try the link with adb to see what happens.
- Mid
- I fire the intent with adb shell am start -a android.intent.action.VIEW -d with the URL, and log state.uri in the redirect to confirm Flutter received the path. The most common cause is the redirect running before the session is restored, so it sends the user to /login and drops the original location. I fix that with a restoring state, refreshListenable, and a from query parameter that the redirect uses after login. If the order screen opens but back closes the app, the route is not nested under its parent.
- Senior
- I separate the Android side from the Flutter side. On Android, I check that the intent reaches the app at all: for https App Links that means android:autoVerify, a correct assetlinks.json with the release signing certificate fingerprint, and checking verification state with adb shell pm get-app-links. If verification fails, Android shows a chooser or opens the browser instead. I also confirm no third-party deep-link plugin is fighting Flutter's built-in handler, which is what the flutter_deeplinking_enabled flag controls. On the Flutter side, I log the location in redirect and the stack in a NavigatorObserver, then lock the fix in with an integration test that launches with the deep link.
What happens to a StatefulWidget's State when go_router removes its route, and what can go wrong?
- Junior
- The route's widgets are removed from the tree and State.dispose() runs. Timers and stream subscriptions must be cancelled there or they keep running after the screen is gone.
- Mid
- When the location changes, go_router rebuilds the Navigator's page list. Pages that are no longer in the list have their routes disposed, their elements unmounted, and State.dispose() called, whether the cause was pop, go, or a redirect. The usual bug is a subscription created later in a callback and stored in a local variable, so dispose never cancels it. I keep every subscription in a field and cancel all of them in dispose.
- Senior
- I treat dispose as the only cleanup point and make ownership explicit: resources live in fields of the State, or better in a state holder (a Riverpod provider with autoDispose, or a Bloc closed with its scope) so the widget does not own long-lived streams at all. Async callbacks check mounted before calling setState. I enable the cancel_subscriptions lint, and I verify in a debug build by navigating away through every path, including notification deep links that call go, and watching the logs and the DevTools memory view to confirm the State and its subscriptions are released.
What happens, step by step, when Dart calls MethodChannel.invokeMethod on Android?
- Junior
- Dart sends the method name and arguments to the Android side. The Kotlin handler registered with setMethodCallHandler runs and calls result.success or result.error, and Dart gets the answer back as a Future.
- Mid
- The arguments are encoded by StandardMethodCodec into a binary message and sent through the engine's BinaryMessenger. On Android the MethodCallHandler runs on the main thread, switches on call.method, and must reply once with success, error, or notImplemented. Dart receives a Future<T?>; error becomes a PlatformException and notImplemented becomes a MissingPluginException. Because the handler is on the main thread, slow work must move to a background thread before replying.
- Senior
- I treat a channel like a network API between two runtimes: messages are copied and encoded, every call is asynchronous, and the contract is only as strong as the strings on both sides. I keep one Dart wrapper per channel so the rest of the app never sees raw channels, use stable error codes, and move blocking work off the main thread with coroutines or a background TaskQueue. For anything bigger than a couple of methods I use Pigeon so the contract is generated and type-checked. I test the Dart side with setMockMethodCallHandler and the Kotlin side with unit tests around the handler logic.
How does EventChannel differ from MethodChannel, and when would you use each?
- Junior
- MethodChannel is for a single request and reply, like reading a setting. EventChannel is for a stream of values from Android, like sensor updates.
- Mid
- On the Dart side you call receiveBroadcastStream() and listen. On Android you implement StreamHandler: onListen gives you an EventSink to send success or error events, and onCancel runs when Dart cancels. I start the native work, such as registering a sensor listener, in onListen and stop it in onCancel. The classic bug is never cancelling the Dart subscription, so onCancel never runs and the sensor stays on.
- Senior
- The Dart listener owns the lifecycle: listening starts native work and cancelling stops it, so I tie the subscription to a widget's dispose or a state holder's close. I keep event payloads small and the rate reasonable, because each event is encoded and copied across the channel; high-rate data like camera frames belongs in a Texture, and synchronous C APIs in dart:ffi. Events are sent from the main thread, so if the native source produces values on a background thread I post them to the main looper before calling the sink.
When would you choose Pigeon over a raw MethodChannel?
- Junior
- Pigeon generates type-safe code for both Dart and Kotlin from one definition, so you do not write method-name strings and maps by hand. I would use it when the data is more than a couple of simple values.
- Mid
- With a raw MethodChannel, structured data becomes Map<String, dynamic> on the Dart side and a Map on the Kotlin side, and any renamed key fails at runtime. Pigeon generates data classes, the codec, and an interface to implement in Kotlin, for calls from Dart to native (@HostApi) and from native to Dart (@FlutterApi). The cost is a code-generation step and generated files to keep in sync.
- Senior
- Raw channels can already call in both directions, so the reason for Pigeon is the contract, not capability. Once a channel has several methods or nested types, or Flutter and Android code are owned by different people, generated code turns protocol drift into compile errors on both sides. I keep the Pigeon definition in the repo, regenerate it in CI or check that generated files are up to date, and still wrap the generated API in a small Dart class so the rest of the app depends on our own types.
How do you debug a MissingPluginException on Android?
- Junior
- It means no handler answered the call. I check that the channel name is spelled the same on both sides and that the handler is registered.
- Mid
- For a published plugin, the usual cause is adding the dependency and only hot restarting; native code needs a full rebuild with flutter run. For my own channel I check the exact channel string, that setMethodCallHandler runs in configureFlutterEngine before Dart calls it, and that the handler does not return notImplemented for that method name, which also surfaces as MissingPluginException.
- Senior
- I check which FlutterEngine the Dart code is running on. Handlers registered in MainActivity.configureFlutterEngine are not present on a separate engine, such as a cached engine created elsewhere or one started for background work, so the channel must be registered there too, ideally by packaging it as a FlutterPlugin so registration happens for every engine. I add a log line in the handler to confirm it is reached, and I write a Dart test with a mocked handler to confirm the wrapper maps the exception to a sensible app error.
What happens when you call setState in a StatefulWidget?
- Junior
- It marks the State as dirty, and on the next frame Flutter calls build again. The new widgets are compared with the old ones, and only the parts of the screen that changed are updated.
- Mid
- setState schedules a frame and marks the element dirty. During the build phase, build runs and returns new child widgets. For each child the element checks: if it is the identical instance, as with a const widget, it skips it; if the runtimeType and key match, it updates the existing element and render object; otherwise it replaces them. Render objects whose properties changed are marked for layout or paint. The common pitfall is calling setState high in the tree so far more widgets rebuild than needed.
- Senior
- Rebuilding widgets is usually cheap; the expensive parts are large build methods, unnecessary layout, and costly painting. So I measure first: a profile-mode trace in DevTools, with widget build tracking turned on, shows which widgets rebuild and whether the time goes to the UI thread or the raster thread. Then I shrink the rebuild scope by moving state down, splitting widgets, or using selectors in Riverpod or Bloc, and keep build methods free of heavy work. const is a small win on top, not the main tool.
What is shader compilation jank, and how does Impeller change things?
- Junior
- It is a stutter the first time an effect like a blur or shadow is drawn, because the GPU shader for it has to be compiled at that moment. After that it is cached, so the stutter only happens once. Impeller avoids it by compiling shaders ahead of time.
- Mid
- With the legacy Skia renderer, shaders were generated and compiled at runtime when an effect first appeared, which could take longer than a frame and showed up as a raster-thread spike. Impeller compiles a fixed set of shaders when the engine is built, so nothing compiles during frames. Impeller is the only renderer on iOS and the default on Android API 29 and newer; older Android devices still use the legacy renderer, so shader jank can still appear there.
- Senior
- I treat it as a device-matrix question. On Impeller devices I look for other raster costs, such as heavy blurs, saveLayer from opacity or clips, and large images. For apps that support older Android, I keep a pre-API-29 device in testing, reproduce first-run behaviour in profile mode with --purge-persistent-cache, and look for frames DevTools marks as shader compilation. If an effect is too expensive there, I simplify it on those devices rather than ship a stutter. I confirm with before-and-after traces rather than guessing.
When would you use RepaintBoundary and when would it hurt?
- Junior
- RepaintBoundary gives a subtree its own layer, so when that subtree repaints, the rest of the screen does not have to. It helps around something that animates inside an otherwise static screen.
- Mid
- I use it when a small area repaints often next to a large area that does not, for example a spinner or a ticking timer inside a complex card. Each boundary is a separate layer, which costs memory and compositing time, so wrapping everything can make things slower. ListView and GridView already add a RepaintBoundary around each item, so adding another around list items is redundant.
- Senior
- I decide with evidence: Highlight repaints in DevTools shows which regions repaint each frame, and the frame chart shows whether raster time drops after adding a boundary. A boundary helps when its contents repaint independently of the surroundings; it hurts when the contents and the parent always repaint together, because then you pay for an extra layer with no saving. I also check whether a widget I am using, such as a list or a route, already inserts one.
Explain the widget, element, and render object trees in Flutter.
- Junior
- Widgets are immutable descriptions of the UI. Elements are the live instances that hold State and connect widgets to the screen. Render objects do layout and painting. Widgets are recreated often; elements and render objects are reused.
- Mid
- Widgets are cheap configuration objects. Each widget in the tree is backed by an element, which keeps its position and any State. Elements for render-object widgets, like Padding or Row, own a RenderObject; elements for StatelessWidget and StatefulWidget own none and only build children. On rebuild, elements compare new widgets with old ones by identity, then by runtimeType and key, and update or replace render objects accordingly. This is close to how Compose keeps a slot table and only updates nodes whose inputs changed.
- Senior
- The split lets Flutter rebuild widgets freely while keeping the expensive objects stable: elements preserve state across rebuilds, and render objects only redo layout or paint when a property actually changes. Keys control element matching, which is why a list of stateful items needs keys when items move. In practice I use the Inspector to see the widget tree, widget build tracking to see rebuilds, and the layout explorer and paint highlighting to find unexpected layout or paint work. Knowing which tree a cost lives in tells me whether the fix is a smaller rebuild scope, a cheaper layout, or less painting.
React Native
How does TypeScript handle null safety compared to Kotlin?
- Junior
- Kotlin has one empty value, null. TypeScript has two: null and undefined. With strictNullChecks on, the compiler makes you handle both before using a value, much like Kotlin's nullable types.
- Mid
- Kotlin builds nullability into every type: String? and String are different types. TypeScript gets close with strictNullChecks, but null and undefined are separate types, and optional properties (email?: string) give undefined, not null. So I check with == null or use ?? and ?. which cover both. The ! operator looks like Kotlin's !!, but it is only a compile-time assertion with no runtime check.
- Senior
- Kotlin's null safety is enforced by the compiler and backed by runtime checks at Java boundaries. TypeScript's types are erased, so any, as casts and ! can all make the types lie, and API data typed with as is never checked. On a team I enforce strict: true, lint rules such as no-explicit-any and consistent-type-assertions, tsc in CI on every PR, and schema validation at the network boundary so the types match reality. Remaining null bugs show up as JS TypeErrors, so I also want error boundaries and crash reporting for JS errors.
What is the difference between async/await in JavaScript and coroutines in Kotlin?
- Junior
- Both let you write asynchronous code that reads top to bottom without nested callbacks. JavaScript uses async functions and Promises; Kotlin uses suspend functions and coroutines.
- Mid
- Kotlin coroutines have structured concurrency: a scope cancels its children when it is cancelled, failures propagate to the parent, and withTimeout enforces a deadline. A JavaScript Promise has no parent and cannot be cancelled from outside; fetch supports an AbortController, and other work needs a manual flag. A Promise also starts as soon as it is created, so it behaves more like a Deferred from async {} than like a suspend call.
- Senior
- JavaScript runs on a single-threaded event loop, so await gives up the thread the way suspension does, but there is no scope tying work to a lifecycle. In React Native I tie cancellation to the component lifecycle myself: abort in the useEffect cleanup, or let TanStack Query manage it, since its query function receives an AbortSignal. In code review I look for fetches with no abort or ignore logic in effects, floating promises (no-floating-promises lint), and missing catch handlers, because nothing like a parent scope will surface the failure.
Explain the closure capture bug in JavaScript loops and why Kotlin developers rarely hit it.
- Junior
- If you use var in a for loop and create a closure inside it, all closures share one variable and see the final value. Using let creates a new variable per iteration, which fixes it.
- Mid
- Kotlin's for loop variable is a new val on each iteration, which is what let gives you in JavaScript. var is function-scoped, so one variable is shared by the whole loop. The bug shows up in timers or callbacks registered in a loop: every callback sees the last index.
- Senior
- Closures in both languages capture variables, not values: a Kotlin lambda capturing a var sees later changes too. The JavaScript difference is that var is hoisted to the function, so the loop has a single variable. Modern TypeScript with an ESLint no-var rule removes the problem, and array methods like map and forEach avoid it because each callback call has its own parameter. In React the same idea appears as stale closures: a callback created in an earlier render keeps that render's values.
How do discriminated unions in TypeScript compare to sealed classes in Kotlin?
- Junior
- Both model a fixed set of cases. A Kotlin sealed class has subclasses; a TypeScript discriminated union is a union of object types that share a tag field. You handle each case with when in Kotlin or switch in TypeScript.
- Mid
- A sealed class exists at runtime, so is checks work and the compiler checks when for exhaustiveness. A discriminated union exists only at compile time: the tag is a string literal type, and the compiler narrows the type in each switch case. To get exhaustiveness you assign the value to never in the default case. Redux actions, reducer state and event payloads usually use this pattern.
- Senior
- Because TypeScript is structural and erased, any object with the right tag counts as that member, and nothing checks a payload from the network or a native module at runtime. So I validate at the boundary, keep the never check in every switch so adding a member breaks the build in all the right places, and treat as casts on union types as a review red flag. Kotlin gives each subclass a distinct runtime identity; in TypeScript the tag is the only identity you have.
What is the difference between props and state?
- Junior
- Props are passed from a parent component to a child and are read-only for the child. State is owned by the component itself through useState, and changing it re-renders the component.
- Mid
- Props are like composable parameters and state is like remember { mutableStateOf() }. A child that needs to change something calls a callback prop and the parent updates its own state, which is the same as state hoisting in Compose. A state variable is a snapshot for the current render, so reading it right after calling the setter still gives the old value.
- Senior
- The question is really about ownership. Each piece of state should live in the lowest component that all its readers share, and anything derivable from props or other state should be calculated during render rather than stored, otherwise you get synchronisation bugs. When state has to travel far, I choose between lifting it, Context (which re-renders every consumer when the value changes) and an external store with selectors, depending on how often it changes and how many components read it.
How does the useEffect dependency array work?
- Junior
- It lists the values the effect uses. React runs the effect again when one of them changes. An empty array means it runs after the first render.
- Mid
- After each render React compares every dependency with its previous value using Object.is. If any differ, it runs the previous cleanup and then the effect again. No array means after every render; an empty array means once after mount, although StrictMode in development runs setup, cleanup, setup once to check that cleanup works.
- Senior
- Because the comparison is by reference, an object or function created in the component body is new every render and makes the effect run every time. I fix that by moving the value inside the effect, depending on primitive fields instead of the object, or memoizing it. I treat the dependency list as a description of what the effect reads, enforced by exhaustive-deps, not as a way to control when it runs; if I want it to run less often, I change the code so it reads less.
What is a stale closure in the context of React hooks?
- Junior
- It is when a function uses an old value of a state variable instead of the current one.
- Mid
- Every render creates new functions that capture that render's props and state. If an effect, timer or memoized callback was created in an earlier render and not recreated, it still sees the old values. A missing dependency in useEffect or useCallback is the usual cause.
- Senior
- Each render is a snapshot, and closures capture that snapshot. The fixes depend on the case: add the dependency so the function is recreated, use the updater form setCount(c => c + 1) so you do not need the current value, or keep the latest value in a ref when a long-lived callback must read it without restarting a subscription. Kotlin developers meet the same idea in Compose with rememberUpdatedState, which exists for exactly this problem in LaunchedEffect.
When should you use useMemo or useCallback?
- Junior
- To avoid redoing work on every render: useMemo remembers a computed value and useCallback remembers a function.
- Mid
- useMemo is for calculations that are noticeably expensive, such as filtering or sorting a large list. useCallback keeps a function's identity stable so a React.memo child can skip re-rendering, or so an effect that depends on the function does not re-run.
- Senior
- Both cost memory and code complexity and only help when something compares by reference, so I add them where profiling or a memo child shows a need, not everywhere. React treats them as performance hints, not guarantees, so correctness must never depend on them. If the project uses the React Compiler, most manual memoization is unnecessary because the compiler adds it at build time.
How do you decide where a piece of state lives in a React Native app?
- Junior
- If only one component uses it, I keep it in useState. If many screens need it, I put it in a global store like Zustand or Redux Toolkit.
- Mid
- I split it by source. UI state that one component owns stays local. Client state shared across screens, like the session or theme, goes into Context if it rarely changes, or a store with selectors if it changes often. Data from the backend goes into TanStack Query, because it is a cache of someone else's data and needs refetching and invalidation.
- Senior
- I start from ownership and lifetime: who writes it, who reads it, and whether it must survive navigation, process death or offline use. Server state belongs to a cache layer with clear keys and invalidation rules, and persisting it is a cache decision, not a store decision. Client state goes in the smallest scope that works, because global stores make components harder to reuse and test. It mirrors Android: remember for UI elements, a ViewModel or state holder for screen and app state, and a repository as the single source of truth for data.
How does React Navigation handle the Android back button?
- Junior
- The native stack keeps a stack of screens, and pressing back pops the top one. On the first screen, back leaves the app.
- Mid
- React Navigation listens to back presses through React Native's BackHandler. The focused navigator tries to go back first; if it cannot, the event goes to its parent navigator. If nothing can go back, the system handles it. Screens can intercept back themselves, for example with the usePreventRemove hook to confirm discarding unsaved changes.
- Senior
- Navigation state is a plain, serializable object per navigator, nested for nested navigators, and back is an action dispatched to the focused navigator that bubbles up to parents if not handled. That is why overlays that are not screens or Modals ignore back, and why params should be serializable: the same state is used for persistence and for deep links configured through the linking prop. I test back, the predictive back gesture and deep links on Android specifically, because iOS-first teams often miss them.
Why use TanStack Query instead of fetching data in a useEffect?
- Junior
- It handles loading and error states and caches the result so the app does not fetch the same data again and again.
- Mid
- A hand-written useEffect fetch needs its own loading and error state, race handling, cancellation and caching. TanStack Query does all of that per query key: screens that use the same key share one cached result, duplicate requests are deduplicated, and data is refetched when it is stale and on triggers such as reconnecting or invalidation after a mutation.
- Senior
- It turns server data into a cache with explicit keys and freshness rules instead of scattered component state. I configure staleTime per kind of data, invalidate precise keys after mutations or use optimistic updates with rollback, and pass the AbortSignal from the query function to fetch so abandoned requests are cancelled. In React Native I also wire its focus and online managers to AppState and the network status, since there is no browser window focus event.
What makes a global store slow in React Native, and how do you fix it?
- Junior
- If too many components re-render whenever the store changes, the app can feel slow.
- Mid
- Components that read the whole store or a large object re-render on every change, even when the field they show did not change. Selecting only the needed slice with a selector, and splitting unrelated state, keeps re-renders small.
- Senior
- Re-rendering runs on the JS thread, so unnecessary renders delay touch handling and JS-driven animations. With Zustand or Redux I use narrow selectors and shallow comparison for derived objects; with Context I split providers and memoize the value, since every consumer re-renders when it changes. I confirm the problem with the React DevTools profiler before optimising, and keep fast-changing values such as scroll position out of global state.
What is the difference between the old React Native bridge and JSI?
- Junior
- The old bridge sent JSON messages asynchronously between JS and native. JSI is a C++ API that lets JS call native code directly, without serializing to JSON, and it allows synchronous calls.
- Mid
- The bridge serialized each call to JSON, queued it and delivered it in batches, so native code could never return a value in the same call. With JSI, JS holds references to C++ host objects and calls their methods directly with typed arguments. Sync vs async is now chosen per method by the spec: a plain return type is synchronous, a Promise is asynchronous. The pitfall is that a slow synchronous method blocks the JS thread.
- Senior
- JSI is engine-agnostic, so it works with Hermes or JSC; it also underpins Fabric and lets libraries such as Reanimated run code on other threads. In a migration I check that no synchronous method does I/O, that heavy async work runs on its own executor, and I confirm in a Perfetto trace that the JS thread is not stuck in native calls during startup or interaction. Since 0.82 the legacy bridge cannot be enabled at all, so remaining legacy modules depend on the interop layer and are worth migrating to typed specs.
What are TurboModules and how do they differ from legacy native modules?
- Junior
- TurboModules are the New Architecture's native modules. You describe the API in a TypeScript spec, Codegen generates a base class, and you implement it in Kotlin. Legacy modules extended ReactContextBaseJavaModule directly and used @ReactMethod.
- Mid
- TurboModules are lazy: the native instance is created the first time JS requests the module rather than at startup, which helps startup time when an app has many modules. They are called through JSI instead of the bridge, and the generated spec gives compile-time checks on the Kotlin side. Registration goes through a BaseReactPackage with ReactModuleInfo marking isTurboModule = true.
- Senior
- Because the spec is the single contract, I treat it as an API boundary: return types decide threading, nullable types decide how Kotlin must handle null, and changing it regenerates the base class so the Kotlin compiler catches drift. I keep constructors cheap because they run on first use, use needsEagerInit only for modules that truly must start early, and resolve or reject every Promise exactly once. For a required module I use getEnforcing and a CI smoke test so a missing registration never reaches users.
What does Fabric change for an Android developer?
- Junior
- Fabric is the New Architecture's renderer. It replaces the old UIManager that sent view updates over the bridge. React components still become native Android views.
- Mid
- Fabric moves the shadow tree into C++. React renders on the JS thread, the commit phase runs Yoga layout, and the mount phase applies the changes to Android views on the UI thread. Because it uses JSI it can render synchronously when needed and supports React's concurrent features. Custom native components still use a ViewManager on Android, now with a Codegen-generated interface and delegate.
- Senior
- The three phases matter for debugging: a slow render is JS work, slow layout points at deep or complex Yoga trees, and slow mount shows up on the UI thread in a Perfetto trace. Old Java ReactShadowNode subclasses do not work under Fabric; custom layout now needs a C++ shadow node, so I avoid it unless a component genuinely needs custom measurement. For a component library I write a TypeScript component spec with codegenNativeComponent and implement the generated ManagerInterface so props are type-checked.
How does Codegen work and what does it produce on Android?
- Junior
- Codegen reads a typed spec written in TypeScript or Flow and generates native code from it. On Android you get a base class to implement, so you do not write the glue by hand.
- Mid
- You add a codegenConfig block to package.json with a name, type, jsSrcsDir and android.javaPackageName. On Android, Codegen runs during the Gradle build through the generateCodegenArtifactsFromSchema task and produces an abstract Java spec class plus JNI and C++ bindings. Spec files must use the Native prefix. A common pitfall is a stale build after changing the spec; a clean build regenerates the files.
- Senior
- Codegen supports a limited set of types (primitives, typed objects, arrays, Promise, callbacks and a few others), so I design specs around those rather than passing untyped blobs. For a library I make sure codegenConfig is in the library's package.json so apps generate the code on install, and I read the generated Java under the build directory when a signature mismatch is unclear. Keeping the spec small and typed makes the generated contract easy to review in pull requests.
What triggers a re-render in React Native and how do you prevent unnecessary ones?
- Junior
- A component re-renders when its state changes, when its parent re-renders, or when a context it reads changes. Wrapping a child in React.memo lets it skip re-rendering when its props have not changed.
- Mid
- Any state update re-runs the component and, by default, all its children. React.memo does a shallow prop compare, so it only helps if props are referentially stable; a new object, array or inline function each render defeats it. useMemo and useCallback keep those references stable. In FlatList that means a memoized row, a stable renderItem, and extraData for any state renderItem reads.
- Senior
- I start from measurement: the React Profiler in React Native DevTools shows which components rendered and why, and highlighting updates shows wasted renders while interacting. Common fixes are moving state down so fewer components own it, splitting contexts so a frequently changing value does not re-render every consumer, and passing primitives instead of whole objects to rows. I avoid wrapping everything in useMemo and useCallback, because each has a cost and a dependency array that can go stale; I add them where the profiler shows a measurable gain.
How does FlatList work and which props matter for performance?
- Junior
- FlatList only renders the items near the screen instead of the whole list, so a list with thousands of items does not create thousands of views at once.
- Mid
- FlatList is built on VirtualizedList and a ScrollView. It mounts items in a window around the viewport (windowSize, in viewport heights) and unmounts the rest, rendering in batches (initialNumToRender, maxToRenderPerBatch). getItemLayout removes async measurement for fixed-size rows, a stable keyExtractor keeps row identity correct, and removeClippedSubviews, already on by default on Android, detaches off-screen views. Unlike RecyclerView it does not recycle views.
- Senior
- The props are trade-offs between blank areas, responsiveness and memory: a larger window or batch means fewer blank areas but more JS work and memory. I tune them per screen on a real mid-range device rather than copying values. When rows are complex and the list is long, I compare against FlashList, which recycles row components the way RecyclerView recycles view holders. I also make the row itself cheap, with small thumbnails and shallow trees, because every row that enters the window is mounted from scratch.
Why use react-native-reanimated instead of JS-driven Animated values?
- Junior
- Reanimated runs animations on the UI thread, so they stay smooth even when the JS thread is busy. JS-driven Animated values are updated from JavaScript and can stutter.
- Mid
- A JS-driven animation needs the JS thread for every frame, so it competes with rendering and event handling. Animated with useNativeDriver: true moves the animation to the UI thread, but only for non-layout props such as transform and opacity. Reanimated runs worklets on the UI thread and supports layout props, gestures and scroll handlers through useAnimatedScrollHandler and useAnimatedStyle.
- Senior
- Worklets are small functions that run on the UI thread with shared values as their state, so the animation and the gesture stay in sync without a JS round trip. The trade-offs are an extra native dependency, rules about what a worklet may capture, and the need to call back to JS explicitly for side effects. For a one-off fade on press, Animated with the native driver is enough; for gesture-driven or scroll-linked motion I use Reanimated, usually with react-native-gesture-handler, and confirm in a trace that the JS thread is not on the per-frame path.
How do you profile a slow React Native screen on Android?
- Junior
- I open React Native DevTools, record with the React Profiler while using the screen, and look for components that render more often than they should. The Perf Monitor overlay from the Dev Menu also shows whether frames are dropping.
- Mid
- First I reproduce the problem on a release build on a real device, because debug builds run React in development mode and feel slower than production. To find extra renders I use the React Profiler in a development build. To see which thread is busy I record a Perfetto trace and check whether the JS thread or the UI thread is saturated during the slow interaction.
- Senior
- I separate the problem into phases: a long JS thread means rendering or business logic, and I go to the profiler; a busy UI thread with an idle JS thread points at mounting, heavy views, images or overdraw, which I inspect with Perfetto and Android Studio's tools. I fix one thing at a time and re-measure on the same device and build type, and I add production monitoring for startup and slow frames so regressions show up after release, not only in my local traces.