Animations in depth

Learn Jetpack Compose animations in depth: animate*AsState, updateTransition, AnimatedVisibility, AnimatedContent, Animatable and deferred reads. About 25 minutes.

Why it matters

  • Animations run every frame. Reading an animated value in the wrong phase makes Compose recompose 60 or more times a second, which is a common source of jank on Android.
  • Compose has several animation APIs, and senior interviews ask which one fits: animate*AsState, updateTransition, AnimatedVisibility, AnimatedContent, Animatable or rememberInfiniteTransition.
  • Gesture-driven UI (drag to dismiss, swipe, fling) needs Animatable, because it can snap to the finger and continue with the gesture's velocity.
  • Small details decide whether an exit animation plays at all, whether two properties stay in sync, and whether an interrupted animation jumps or flows.

The simple explanation

  • animate*AsState is a thermostat: you set the target, it moves there smoothly, and if you change the target halfway it turns around without a jump.
  • updateTransition is a conductor: one state change, many properties moving together.
  • Animatable is driving by hand: you decide when to snap, when to animate, and with what starting speed.
  • rememberInfiniteTransition is a metronome: it keeps going while it is in the composition.

How do animations work in Jetpack Compose? An animation API holds a value in Compose state and updates it once per frame until it reaches its target. Whatever reads that state gets updated. If the read happens in a composable body, that scope recomposes every frame; if it happens inside a lambda modifier such as graphicsLayer { }, offset { } or drawBehind { }, only layout or draw re-runs. All Compose animations are interruptible: a new target starts from the current value and velocity.

APIUse it forNotes
animateFloatAsState, animateDpAsState, animateColorAsStateOne value following a targetSimplest; returns State<T>
updateTransition(targetState)Several values driven by one stateKeeps properties in sync; visible in Android Studio's Animation Preview
AnimatedVisibilityEnter and exit of contentKeeps content composed until the exit animation ends
AnimatedContentSwapping content when a target changestransitionSpec returns a ContentTransform (enter togetherWith exit)
Modifier.animateContentSize()Smooth size change of one elementAnimates layout size
AnimatableGestures, sequences, imperative controlanimateTo, snapTo, animateDecay; suspend functions in a coroutine
rememberInfiniteTransitionLooping effects such as pulses and shimmersRuns while it is in the composition

Specs decide the motion: spring() (the default for most APIs, physics-based, keeps velocity on interruption), tween(durationMillis, easing) for fixed timing, keyframes { } for set points, and infiniteRepeatable for loops.

Shared element transitions use SharedTransitionLayout with Modifier.sharedElement() or sharedBounds() inside AnimatedVisibility, AnimatedContent or Navigation Compose destinations. These APIs started as experimental, so check whether your Compose version still needs @OptIn(ExperimentalSharedTransitionApi::class).

Notes

  • Read animated values inside graphicsLayer { }, offset { } or drawBehind { } when you can. Reading in graphicsLayer skips composition and layout and only redraws.
  • Modifier.alpha(value) or Modifier.offset(x.dp) with a parameter reads the value in composition. Use the lambda versions for values that change every frame.
  • Animating Modifier.size() or padding() changes layout every frame. If the change is purely visual, graphicsLayer { scaleX = ...; scaleY = ... } is cheaper, but it does not move neighbours.
  • animate*AsState handles interruption well: changing the target mid-way continues from the current value and velocity. Use Animatable when you need to snap to a gesture, run steps in sequence, or start with a fling velocity.
  • Animatable.animateTo suspends until the animation ends and cancels any running animation on the same Animatable. Run it from rememberCoroutineScope() in callbacks or from LaunchedEffect.
  • After a drag, pass the velocity from VelocityTracker to animateTo(target, initialVelocity = v) or use animateDecay(v, splineBasedDecay(density)) for a fling.
  • Do not wrap AnimatedVisibility in if (visible). When visible turns false the whole block leaves the composition at once and the exit animation never plays.
  • updateTransition keeps several properties on one timeline and shows them together in Android Studio's Animation Preview. Give every animation a label so it is easy to find there.
  • Avoid hand-written loops with delay(16) to animate a value. Animation APIs follow the real frame clock and the device's animator duration scale, which tests can also control.

Code example

A card that expands on tap. updateTransition drives the corner radius and elevation-like scale together, AnimatedVisibility shows details, and a drag handle uses Animatable to follow the finger and spring back.

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.offset
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
 
@Composable
fun ExpandableCard(title: String, details: String) {
    var expanded by remember { mutableStateOf(false) }
 
    // One state, two properties on the same timeline
    val transition = updateTransition(targetState = expanded, label = "card")
    val corner by transition.animateDp(label = "corner") { if (it) 4.dp else 16.dp }
    val scale by transition.animateFloat(label = "scale") { if (it) 1.03f else 1f }
 
    // Imperative control for the drag
    val dragX = remember { Animatable(0f) }
    val scope = rememberCoroutineScope()
 
    Column(
        Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .offset { IntOffset(dragX.value.roundToInt(), 0) } // read in layout
            .graphicsLayer { scaleX = scale; scaleY = scale }  // read in draw
            .background(Color(0xFFE8EAF6), RoundedCornerShape(corner))
            .pointerInput(Unit) {
                detectHorizontalDragGestures(
                    onHorizontalDrag = { _, dx -> scope.launch { dragX.snapTo(dragX.value + dx) } },
                    onDragEnd = { scope.launch { dragX.animateTo(0f, spring()) } },
                )
            }
            .clickable { expanded = !expanded }
            .padding(16.dp)
    ) {
        Text(title)
        AnimatedVisibility(
            visible = expanded,
            enter = fadeIn() + expandVertically(),
            exit = fadeOut() + shrinkVertically(),
        ) {
            Text(details, Modifier.padding(top = 8.dp))
        }
    }
}
  • corner and scale come from one Transition, so they start and finish together and appear as one entry in Animation Preview.
  • dragX is read inside offset { } and scale inside graphicsLayer { }, so dragging and scaling do not recompose ExpandableCard. corner is read in composition because RoundedCornerShape takes a value; that is fine for a short transition, not for a per-frame loop.
  • During the drag, snapTo follows the finger with no animation. On release, animateTo(0f, spring()) springs back. A real swipe-to-dismiss would pass the release velocity as initialVelocity.
  • AnimatedVisibility keeps the details composed while the exit animation runs, then removes them.

Run the idea in plain Kotlin

A model of an interruptible linear tween, frame by frame. Halfway through, the target changes and the animation continues from the current value instead of jumping.

class LinearAnimation(var value: Float) {
  private var start = value
  private var target = value
  private var frame = 0
  private var frames = 0

  fun animateTo(newTarget: Float, durationFrames: Int) {
      start = value // interruption: begin from where we are now
      target = newTarget
      frame = 0
      frames = durationFrames
  }

  fun onFrame(): Boolean {
      if (frame >= frames) return false
      frame++
      val fraction = frame.toFloat() / frames
      value = start + (target - start) * fraction
      return true
  }
}

fun main() {
  val alpha = LinearAnimation(0f)
  alpha.animateTo(1f, durationFrames = 4)

  var n = 0
  while (alpha.onFrame()) {
      n++
      println("frame " + n + ": " + alpha.value)
      if (n == 2) {
          println("user taps again -> new target 0.0")
          alpha.animateTo(0f, durationFrames = 2)
      }
  }
  println("finished at " + alpha.value + " after " + n + " frames")
}

Expected output:

frame 1: 0.25
frame 2: 0.5
user taps again -> new target 0.0
frame 3: 0.25
frame 4: 0.0
finished at 0.0 after 4 frames

In production

Animated badges made a list stutter
  • A list showed a pulsing "new" badge on some rows, implemented with animateDpAsState feeding Modifier.size(badgeSize).
  • Layout Inspector showed those rows recomposing on every frame, and the size change re-measured the row and its neighbours each frame too.
  • On lower-end devices scrolling stuttered whenever badges were visible.
The fix
  • The badge kept a fixed layout size and animated scaleX and scaleY inside graphicsLayer { }, so only drawing re-ran per frame.
  • The pulse moved to rememberInfiniteTransition inside the badge composable, so it exists only while a badge is on screen.
  • Recomposition counts for the rows stopped increasing during the pulse, and a Macrobenchmark scroll test showed fewer slow frames.
Exit animation never played
  • A snackbar-like banner was written as if (showBanner) { AnimatedVisibility(visible = showBanner) { Banner() } }.
  • The enter animation worked, but on dismiss the banner vanished instantly.
  • When showBanner became false, the if removed AnimatedVisibility from the composition in the same frame, so it had no chance to run the exit.
The fix
  • The if was removed: AnimatedVisibility(visible = showBanner) now stays in the composition and handles both directions.
  • For content that must be cleaned up after the exit (such as clearing the message), the team used MutableTransitionState and reacted when isIdle was true and currentState was false.
  • A UI test with the main clock paused advances time and asserts the banner is still shown halfway through the exit.

Common mistakes

  • Reading per-frame values in composition. Modifier.alpha(animatedAlpha) or Modifier.offset(x = animatedX) recompose every frame. Use graphicsLayer { alpha = ... } or offset { IntOffset(...) }.
  • Animating layout properties for a visual effect. Animating size or padding re-measures every frame. Use graphicsLayer scale or translation when neighbours do not need to move.
  • Wrapping AnimatedVisibility in an if. The exit animation cannot run. Pass the condition as visible and keep the composable in the tree.
  • Creating Animatable without remember. A new Animatable with the initial value is created on each recomposition, so the animation keeps restarting.
  • Hand-rolled animation loops. A LaunchedEffect that changes state and calls delay(16) ignores the real frame timing and the system animation scale. Use the animation APIs.
  • Using animate*AsState for gestures. It cannot follow a finger with snapTo or start from a fling velocity. Use Animatable for drag and fling.
  • Ignoring Animation Preview. Unlabelled animations are hard to find there. Pass label to animate*AsState and transition children.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between animateFloatAsState and Animatable?”

“How do you keep animations from causing jank in Compose?”

“What happens if you use Modifier.offset(x = animatedX) instead of Modifier.offset { }?”

“When do you use updateTransition instead of several animate*AsState calls?”

Quiz

You animate alpha with Modifier.graphicsLayer { alpha = animatedAlpha }. What re-runs on each frame?

Which API fits a drag-to-dismiss card that must follow the finger and then fling with the release velocity?

Why does if (visible) { AnimatedVisibility(visible) { ... } } never play its exit animation?

What does updateTransition give you over separate animate*AsState calls?

0 of 4 answered

Mini task

Build a pulse that does not recompose (20 min)

  1. Create the composable. Write @Composable fun PulseDot(color: Color) that draws a 24 dp circle.
  2. Animate it. Use rememberInfiniteTransition(label = "pulse") and animateFloat(1f, 1.3f, infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "scale").
  3. Defer the read. Apply the scale with Modifier.graphicsLayer { scaleX = scale; scaleY = scale } and draw the circle with drawBehind { drawCircle(color) }.
  4. Show it conditionally. In a parent, show PulseDot only when isLive is true, using if (isLive) PulseDot(...) so the infinite animation stops when it is hidden.
  5. Verify. Open Layout Inspector with recomposition counts. Watch PulseDot for ten seconds.
  6. Break it on purpose. Change the scale to Modifier.scale(scale) and watch the count again, then revert.

Done condition: with the graphicsLayer version, PulseDot's recomposition count stays the same while it pulses, and with Modifier.scale(scale) it rises continuously.

Next: Performance: lists and deferred reads