Skip to content

Side effects overview

Side Effects Overview Deep Dive

Overview

Compose separates pure UI description from imperative work. Side-effect APIs exist to run imperative logic safely with composition lifecycle awareness.

Core Concepts

  • keep composable bodies side-effect free
  • use effect APIs for non-UI work
  • choose API by restart/cancellation behavior

Runtime Internals

Effects are scheduled relative to composition and commit phases. Their lifecycle is tied to the composable scope and keys.

Composition / Recomposition Flow

  • composable enters composition
  • effect starts according to API rules
  • key changes can restart effect
  • leaving composition cancels/disposes effect

State Management

Use state as input for effect decisions, but avoid writing loops where effect updates state that immediately restarts itself.

Code Examples

@Composable
fun AnalyticsScreen(screenName: String) {
    SideEffect {
        analytics.setCurrentScreen(screenName)
    }
}

Common Interview Questions

  • Q: Why not launch coroutines directly in composable body? A: Explain runtime behavior: what invalidates state, how recomposition is scoped, where side effects live, and how to verify frame stability with profiler traces.
  • Q: Which effect API runs after commit? A: Answer from runtime mechanics: state ownership, recomposition triggers, effect lifecycle, and frame-time impact measured with tooling.
  • Q: How do keys impact effect restarts? A: Answer from runtime mechanics: state ownership, recomposition triggers, effect lifecycle, and frame-time impact measured with tooling.

Production Considerations

  • keep effects idempotent when possible
  • isolate long-running work to proper scopes
  • document key choices in sensitive effects

Performance Insights

Unnecessary restarts can cause extra work and UI jank, especially if effect work touches I/O or expensive observers.

Senior-Level Insights

Senior candidates explain effect lifecycle semantics clearly and pick APIs based on deterministic cleanup and restart guarantees.