New Tools To Simplify Common Side Effects In Jetpack Compose

Jetpack Compose 1.9, released in August 2025, introduces two game-changing visibility modifiers—Modifier.onVisibilityChanged and Modifier.onFirstVisible—bringing precision, performance, and clarity to UI behavior without resorting to tricky LaunchedEffect hacks.

1. Modifier.onVisibilityChanged

Want to auto-play videos, start animations, or trigger logic as your composable appears or disappears? This modifier lets you react to visibility changes—with optional thresholds for time and visible fraction to avoid rapid, unwanted triggers.

Usage example:

LazyColumn {
  items(feedData) { video ->
    VideoRow(
      video,
      Modifier.onVisibilityChanged(
        minDurationMs = 500,
        minFractionVisible = 1f
      ) { visible ->
        if (visible) video.play() else video.pause()
      }
    )
  }
}

This ensures a video plays only when fully visible (100%) for at least 500 milliseconds—ideal for smooth, efficient UI behavior

2. Modifier.onFirstVisible

Perfect for impression tracking—fires only once, the first time your composable becomes visible (optionally after a minimum duration). Great for analytics, logging, or deferred actions.

Usage example:

LazyColumn {
  items(100) {
    Box(
      Modifier
        .onFirstVisible(minDurationMs = 500) {
          logImpression(it)
        }
        .clip(RoundedCornerShape(16.dp))
        .drawBehind { drawRect(backgroundColor) }
        .fillMaxWidth()
        .height(100.dp)
    )
  }
}

Even in highly dynamic scroll environments, this ensures you log impressions accurately—without false triggers


Why These Modifiers Matter—And What Makes Them Better

No more LaunchedEffect workarounds

Before Compose 1.9, developers often resorted to LaunchedEffect with snapshotFlow or manual visibility logic. Now, visibility handling is built-in, concise, and declarative.

Integrated with onLayoutRectChanged

These modifiers are built on the underlying, efficient onLayoutRectChanged API (introduced in Compose 1.8), so they’re lightweight and accurate.

Avoid misfires thanks to prefetch

With Compose 1.9’s improved lazy list prefetch behavior, LaunchedEffect and DisposableEffect might fire prematurely during off-screen composition. Using onVisibilityChanged and onFirstVisible ensures side-effects only occur when content is truly visible.

smartwatch

Check Best Price At Amazon

Leave a Comment

Your email address will not be published. Required fields are marked *