
compose-state-deferred-reads
Use when Jetpack Compose code reads scroll, animation, gesture, or other frame-rate State in composition, passes changing values across composable boundaries, uses value-form layout/draw modifiers, or back-writes observable state from a later phase into one that's already run.
- Installs
- 989
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/chrisbanes/skills --skill compose-state-deferred-reads- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads compose-state-deferred-reads automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Compose state deferred reads
Core principle
State reads invalidate the phase that reads them. If a State<T> is read in a composable body, changes invalidate composition. If it is read in layout or draw, changes can invalidate only layout or draw. Frame-rate state such as scroll offsets, animations, and drag positions usually belongs in layout/draw, not composition.
Back-writing is the symmetric failure mode: writing observable state from a phase that triggers invalidation of an earlier phase. Compose phases run composition → layout → draw. Writing snapshot-backed state from layout or draw to state read in composition invalidates composition; writing during composition to state read earlier in the same composition does the same. Both schedule extra work — often cascading into sibling lazy items.
The fix is structural: keep the State<T> or a provider lambda and read the value inside a layout/draw callback; capture measurements in callbacks and apply them in the measure phase, not by reading measurement state in sibling composable bodies.
When to use this skill
val x by animate*AsState(...)is passed toModifier.offset(x = ...),Modifier.size(...),Modifier.graphicsLayer(...), or another value-form modifier.LazyListState.firstVisibleItemScrollOffset,ScrollState.value,Animatable.value, or gesture state is read in a composable body.- A composable takes
scrollOffset: Int,progress: Float,dragOffset: Offset, or similar frame-rate values. - Recomposition counters climb during scroll, animation, or gestures even when data is stable.
- A composable body calls
stateMap[key] = …,list.addAll(…), or similar on every recomposition (back-writing composition → composition). - One lazy item captures size with
onSizeChanged/onGloballyPositionedand a sibling reads that height in composition (Modifier.height(state.dp)) — back-writing layout → composition.
0. Back-writing
Back-writing = writing observable state in one phase that triggers invalidation of an earlier (or the current) phase. Compose runs composition → layout → draw, so:
- Writing snapshot state during composition that's read in the same composition.
- Writing snapshot state during layout (e.g. from
Modifier.layout,onSizeChanged,onGloballyPositioned) that's read during composition. - Writing snapshot state during draw that's read during composition or layout.
In all cases the writer schedules extra invalidation passes — often cascading into sibling lazy items.
Do not write to mutableStateOf, mutableStateListOf, mutableStateMapOf, or other snapshot-backed state from the composable body on every pass:
// ❌ BAD — mutates observable map during composition; siblings recompose repeatedly
@Composable
fun MergeOverlay(parent: Map<Key, ViewState>, overlay: Map<Key, ViewState>): Map<Key, ViewState> {
val merged = remember { mutableStateMapOf<Key, ViewState>() }
merged.clear()
merged.putAll(parent)
merged.putAll(overlay) // back-writing composition → composition
return merged
}
// ✅ GOOD — read-only merge; no composition-time writes
@Composable
fun MergeOverlay(parent: Map<Key, ViewState>, overlay: Map<Key, ViewState>): Map<Key, ViewState> =
remember(parent, overlay) {
if (overlay.isEmpty()) parent else parent + overlay
}
Prefer remember(keys) { … } for derived read-only snapshots. Reserve mutableState* writes for event callbacks (onClick) or effects — not for rebuilding derived data on every composition.
Callbacks like onSizeChanged write during layout. That is only safe if no earlier phase reads the resulting state — see cross-row measurement below.
Cross-row measurement (layout → composition back-write)
When row A measures and row B must match A's height, do not read A's captured size in B's composable body. onSizeChanged writes during layout; if B reads it in composition, layout has just back-written into composition:
var anchorHeightPx by remember { mutableIntStateOf(0) }
// ❌ BAD — B reads measurement state in composition; insertion/focus can double-recompose B
RowA(Modifier.onSizeChanged { anchorHeightPx = it.height })
RowB(Modifier.height(with(LocalDensity.current) { anchorHeightPx.toDp() })) // composition read
// ✅ GOOD — capture on A; apply on B in measure phase only
RowA(Modifier.onSizeChanged { if (it.height != anchorHeightPx) anchorHeightPx = it.height })
RowB(
Modifier.decorateMeasureConstraints { incoming ->
if (anchorHeightPx > 0) incoming.copy(minHeight = anchorHeightPx, maxHeight = anchorHeightPx)
else incoming
},
)
decorateMeasureConstraints is a small layout helper (see compose-modifier-and-layout-style). While height is unknown, siblings use a fixed fallback in composition; once known, only layout invalidates — not an extra composition cascade.
1. Prefer block-form modifiers
Several modifiers have value forms and block forms. The value form receives values already read in composition; the block form can read during layout or draw.
// Before: animated value read in composition by the `by` delegate
@Composable
fun SelectionPill(selectedIndex: Int) {
val offsetX by animateDpAsState(120.dp * selectedIndex)
Box(Modifier.offset(x = offsetX))
}
// After: State is kept, value is read in the layout-phase offset block
@Composable
fun SelectionPill(selectedIndex: Int) {
val offsetX = animateDpAsState(120.dp * selectedIndex)
Box(
Modifier.offset {
IntOffset(offsetX.value.roundToPx(), 0)
},
)
}
Common replacements:
| Composition read | Deferred read |
|---|---|
Modifier.offset(x = animatedX) | Modifier.offset { IntOffset(animatedX.value.roundToPx(), 0) } |
Modifier.graphicsLayer(translationY = y) | Modifier.graphicsLayer { translationY = yProvider() } |
val radius by animateFloatAsState(...); drawBehind { drawCircle(radius = radius) } | val radius = animateFloatAsState(...); drawBehind { drawCircle(radius = radius.value) } |
The drawBehind block is already draw-phase; the important part is that the State.value read also happens inside that block.
2. Pass providers across composable boundaries
If the fast-changing value would cross a composable boundary, pass a provider lambda instead of a snapshot value:
// Before: HomeScreen reads scroll offset in composition and passes the value down
@Composable
fun HomeScreen() {
val listState = rememberLazyListState()
LazyColumn(state = listState) {
item { HeroImage(scrollOffset = listState.firstVisibleItemScrollOffset) }
}
}
@Composable
fun HeroImage(scrollOffset: Int, modifier: Modifier = Modifier) {
AsyncImage(
model = "...",
modifier = modifier.graphicsLayer(translationY = -scrollOffset / 2f),
)
}
// After: the only read happens inside graphicsLayer
@Composable
fun HomeScreen() {
val listState = rememberLazyListState()
LazyColumn(state = listState) {
item {
HeroImage(
scrollOffsetProvider = {
if (listState.firstVisibleItemIndex == 0) {
listState.firstVisibleItemScrollOffset
} else {
0
}
},
)
}
}
}
@Composable
fun HeroImage(scrollOffsetProvider: () -> Int, modifier: Modifier = Modifier) {
AsyncImage(
model = "...",
modifier = modifier.graphicsLayer {
translationY = -scrollOffsetProvider() / 2f
},
)
}
Suffix provider parameters with Provider when that clarifies the deferred-read contract.
3. Other layout/draw read sites
State reads can also be deferred inside:
Modifier.layout { measurable, constraints -> ... }- Custom
Alignment.align(...) drawWithContent,drawBehind, and other draw modifiers- Block-form layer/layout modifiers such as
graphicsLayer { ... }andoffset { ... }
Use these when the state changes where something is placed or painted. If the state decides which composables exist, it belongs in composition.
Quick reference
| Symptom | Diagnosis | Fix |
|---|---|---|
val x by animateFloatAsState(...) then Modifier.offset(...) | by reads in composition | Keep State<Float> and read .value in offset {} |
Modifier.graphicsLayer(translationY = animatedY) | Property-argument form uses composition values | Use graphicsLayer { translationY = ... } |
Child(scrollOffset = listState.firstVisibleItemScrollOffset) | Fast-changing value crosses boundary | Child(scrollOffsetProvider = { ... }) |
| Draw block still recomposes every frame | Value was read before draw block | Move the State.value read inside the draw block |
| State chooses between different UI branches | Composition decision | Keep the read in composition |
mergedMap.putAll(overlay) in composable body | Back-writing composition → composition | remember(parent, overlay) { parent + overlay } |
Sibling Modifier.height(measuredPx.toDp()) | Back-writing layout → composition | Measure-phase constraint decoration |
| Identity cache for read-only merge | Stale overlay risk | remember(keys) on immutable result |
When NOT to apply
- The state controls which composables are emitted.
- The animation is one-shot, cheap, and clarity wins.
- You are writing tests where direct value assertions are simpler.
- Runtime evidence shows recomposition is not the bottleneck.
Related
compose-state-authoring— whenmutableState*belongs in composition vs callbacks.compose-state-hoisting— where state-holder vs plain UI split applies when passing providers/lambdas across boundaries.compose-stability-diagnostics— parameter stability and compiler reports.compose-modifier-and-layout-style— measure-phase constraint decoration helper.
FAQ
What does the compose-state-deferred-reads skill do?
Use when Jetpack Compose code reads scroll, animation, gesture, or other frame-rate State in composition, passes changing values across composable boundaries, uses value-form layout/draw modifiers, or back-writes observable state from a later phase into one that's already run.
How do I install compose-state-deferred-reads?
Run npx skills add https://github.com/chrisbanes/skills --skill compose-state-deferred-reads in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/compose-state-deferred-reads/ (personal) or .claude/skills/compose-state-deferred-reads/ (project).
Which AI agents can use compose-state-deferred-reads?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is compose-state-deferred-reads safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains compose-state-deferred-reads?
It is published by chrisbanes in chrisbanes/skills. It has 989 recorded installs.
More from chrisbanes/skills
compose-ui-testing-patterns
chrisbanes/skills
Use when writing or reviewing Jetpack Compose UI tests, screenshot tests or baseline-recording evidence, previews, semantics assertions, fake image loading, keyboard input, focus assertions, interaction state (hover/pressed/focused), or tests for plain state-driven UI composables.
compose-focus-navigation
chrisbanes/skills
Use when writing or reviewing Jetpack Compose UI for TV, keyboard, desktop, accessibility focus, D-pad navigation, FocusRequester, focusProperties, key events, or initial focus behavior.
compose-animations
chrisbanes/skills
Use when writing or reviewing Jetpack Compose motion: visibility enter/exit, animating one property toward a target, color or size transitions, multiple properties from one state, switching composable content, or choosing between AnimatedVisibility, animateAsState, rememberTransition, AnimatedContent, and Crossfade.
shepherd
chrisbanes/skills
Use when asked to shepherd, babysit, monitor, or poll open pull requests or merge requests, including triaging review feedback, CI failures, and routine follow-up.
kotlin-control-flow
chrisbanes/skills
Use when writing or reviewing Kotlin branching and control flow: when expressions, guard conditions, sealed type exhaustiveness, smart casts, nullable branching, early returns, or replacing complex if/else chains.
using-chrisbanes-skills
chrisbanes/skills
Use when routing Kotlin or Jetpack Compose work, or physical Android benchmark evidence that needs a configuration decision, especially when several Kotlin or Compose concerns overlap.
Popular frontend & design skills
setup-matt-pocock-skills
mattpocock/skills
Configure this repo for the engineering skills: set up its issue tracker, triage label vocabulary, and domain doc layout. Run once before first use of the other engineering skills.
frontend-design
anthropics/skills
Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
hyperframes-animation
heygen-com/hyperframes
All animation knowledge for HyperFrames — atomic motion rules, multi-phase scene blueprints, scene transitions, broader motion-design techniques, AND the seven runtime adapters (GSAP default, plus Lottie, Three.js, Anime.js, CSS keyframes, Web Animations API, TypeGPU). Use for any motion or animation task: pick 2-4 rules and compose, or load a blueprint, or look up runtime-specific API (e.g. GSAP eases / Lottie player / Three.js mixer). Also covers auditing an existing composition's choreography (animation map) and 24 named text-animation effects. HyperFrames-native: single paused timeline, seek-safe, deterministic.
prototype
mattpocock/skills
Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.
hyperframes-core
heygen-com/hyperframes
The HyperFrames composition contract — build one renderable project. Use for composition structure, the data- timing attributes, class="clip", tracks, sub-compositions, variables, framework-owned media playback, deterministic-render rules, and validation. Read before writing composition HTML.
vercel-react-best-practices
vercel-labs/agent-skills
React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.