ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Member-only story

The simplest way to understand side effects in compose

Karishma Agrawal
ProAndroidDev
Published in
7 min readOct 18, 2024

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 the Composable function is re-composed. It ensures that code inside it will always run after the Composable 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 the Composable 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 =…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Karishma Agrawal

Android Developer @Eventbrite | Wanted to be a writer so I write code now | Reader

Responses (1)

Write a response