Member-only story
The simplest way to understand side effects in compose

In Jetpack Compose, a modern UI toolkit for Android, side effects are ways to handle changes outside the UI hierarchy that need to be reflected in your Compose functions or to ensure certain actions take place as a result of state changes. Side effects help bridge the gap between the declarative nature of Compose and the imperative interactions that might be needed, such as updating a database, logging, or performing a one-time action.
Key Side Effect APIs in Jetpack Compose
Here’s a breakdown of the main side effect functions provided by Compose and how they are typically used:
1.SideEffect
What is it?
SideEffect
is used to run code whenever theComposable
function is re-composed. It ensures that code inside it will always run after theComposable
function has finished rendering.
Use Case:
- Logging or reporting analytics.
- You want to perform some actions that are related to the UI but don't directly affect its state.
@Composable
fun ExampleSideEffect(name: String) {
Text("Hello, $name")
SideEffect {
Log.d("ExampleSideEffect", "Composed with name: $name")
}
}
- This will log a message every time the name
parameter changes, which means that the ExampleSideEffect
gets recomposed.
2. LaunchedEffect
What is it?
LaunchedEffect
is used for running suspend functions (coroutines) when a particular key changes. It runs its block of code when theComposable
enters the composition and again when its keys change.- It cancels any previous coroutine if the key changes.
Use Case:
- Fetching data from a network or database when a particular state changes.
- Showing a one-time toast message when the UI is first composed.
Example:
@Composable
fun ExampleLaunchedEffect(userId: String) {
var userName by remember { mutableStateOf("") }
LaunchedEffect(userId) {
// Fetch user data when userId changes.
userName =…