tezvyn:

Recomposition: Smart UI Updates in Compose

AI-drafted, machine-checkedSource: developer.android.comintermediate
Recomposition: Smart UI Updates in Compose

Recomposition is how Compose redraws your UI. It intelligently re-runs only the functions whose state has changed, avoiding a full screen refresh. This is triggered automatically when a `State` object that a composable reads is updated.

WHY IT EXISTS: Traditional Android UI required developers to manually find and update specific Views when data changed. This imperative approach is error-prone. Recomposition enables a declarative model: you describe your UI for a given state, and Compose handles updating it automatically when that state changes.

THE MENTAL MODEL: Think of recomposition as a smart diffing tool for your UI functions. During the initial drawing (composition), Compose observes which State objects each composable function reads. When a State's value is updated, Compose flags every function that read it as "invalid" and schedules them to be re-run. It then intelligently applies only the resulting changes to the screen.

HOW IT WORKS: The process has three main steps. First, the initial composition builds the UI and tracks state reads. Second, an event updates a State object (like mutableStateOf(0).value = 1). Third, Compose re-executes only the composables that depend on that state. It skips recomposing functions whose inputs haven't changed, which is a key performance optimization.

WHEN TO USE IT: Recomposition is the default, automatic behavior in Compose. You don't call it directly. You design your UI by creating composable functions that read from State objects. Any dynamic UI, from a simple counter to a complex list, relies on this process.

WHEN NOT TO USE IT: The body of a composable function is the wrong place for certain operations. Avoid expensive calculations, I/O operations, or network calls, as they will re-run on every recomposition. Also, avoid creating side effects (like modifying external objects), as recomposition can be skipped or run multiple times. Use remember for caching expensive objects and LaunchedEffect for side effects tied to the composable's lifecycle.

ONE CANONICAL EXAMPLE: A simple counter. A MutableState<Int> holds the count. A Text composable displays the count by reading state.value. A Button's onClick lambda increments state.value. When the button is clicked, the state changes. Compose detects this and only re-executes the Text composable to display the new number, not the entire screen or even the Button itself.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.