skip to content

In Jetpack Compose, why write a custom modifier with Modifier.Node and ModifierNodeElement rather than Modifier.composed or a @Composable modifier factory?

level: seniorimportance: nice to knowfreq 22%

answer

  1. factories that are never skipped
  2. where CompositionLocals get resolved
  3. a stateless element, a stateful node
  4. update runs only when unequal

basics

~20 s

Modifier.Node is the API Compose's own modifiers use: a stateless ModifierNodeElement creates or updates a long-lived node, nothing runs in composition, and only the affected phase is invalidated. Composable factories never skip and composed { } is no longer recommended.

solid answer

~40 s

A `@Composable` modifier factory runs on every recomposition because a composable with a return value cannot be skipped, it cannot be hoisted out of composition, and it resolves CompositionLocals where it is created rather than where it is applied. `Modifier.composed { }` is no longer recommended for its performance cost. With `Modifier.Node` you write a node class that implements types such as `DrawModifierNode` or `LayoutModifierNode`, plus a `ModifierNodeElement` whose `create()` builds the node and whose `update(node)` mutates it only when the new element is not equal to the old one. The node survives recompositions, gets `onAttach`, `onDetach` and a `coroutineScope` cancelled on detach, and is auto-invalidated only for the phases it touches.

code

kotlin · 27 lines
kotlin
fun Modifier.unreadDot(color: Color, visible: Boolean): Modifier =
    this then UnreadDotElement(color, visible)

private data class UnreadDotElement(
    val color: Color,
    val visible: Boolean,
) : ModifierNodeElement<UnreadDotNode>() {
    override fun create() = UnreadDotNode(color, visible)

    override fun update(node: UnreadDotNode) {
        node.color = color
        node.visible = visible
    }
}

private class UnreadDotNode(
    var color: Color,
    var visible: Boolean,
) : Modifier.Node(), DrawModifierNode {
    override fun ContentDrawScope.draw() {
        drawContent()
        if (visible) {
            val radius = size.minDimension * 0.12f
            drawCircle(color, radius = radius, center = Offset(size.width - radius, radius))
        }
    }
}

go deeper

for a junior

Recall that most custom modifiers are just chains of existing ones, and that new drawing or layout behaviour goes in a Modifier.Node rather than composed.

for a middle

Explain the node, element and factory split, what create and update do, and why the element needs value equality.

for a senior

Write a node that draws or measures, handle CompositionLocal reads with currentValueOf, use the attach lifecycle and coroutineScope correctly, and control invalidation when one node covers several phases.

for a principal

Decide when a shared design-system modifier earns a Modifier.Node implementation and a migration off composed, against the review cost of lower-level code the team must own.

## Four ways to build a custom modifier | Approach | How it looks | When it fits | |---|---|---| | Chain existing modifiers | `fun Modifier.card() = padding(16.dp).clip(shape).background(c)` | the behaviour already exists; you only name a combination | | `@Composable` modifier factory | `@Composable fun Modifier.fade(on: Boolean): Modifier` | you need a composable API such as `animateFloatAsState` | | `Modifier.composed { }` | a factory lambda composed for each element | legacy code; no longer recommended | | `Modifier.Node` | a node class, a `ModifierNodeElement` and a factory | new behaviour: custom drawing, layout, input or semantics | Chaining is always the first choice: `Modifier.clip` itself is a call to `graphicsLayer` with a shape. The interesting question is what to do when the behaviour is new. ## Why composable factories and composed { } cost more A `@Composable` modifier factory is easy to write but carries three costs: - **It is never skipped.** A composable function with a return value cannot be skipped, so the factory runs on every recomposition of its caller. - **It must be called in composition.** It cannot be hoisted into a `val` outside a composable to save allocations, as a plain modifier can. - **CompositionLocals resolve where the modifier is created**, not where it is applied. Create it under one `CompositionLocalProvider` and apply it under another, and it uses the first value. `Modifier.composed { }` was the older answer for stateful modifiers. It still exists and is not marked deprecated, but the documentation no longer recommends it because of the performance problems it created; `Modifier.Node` was designed to replace it. ## The three parts of a Modifier.Node modifier 1. **The node**, a class extending `Modifier.Node` plus one or more node types. It holds the logic and any state, and it survives recompositions and can be reused. 2. **The element**, a `ModifierNodeElement<N>`. It is stateless and immutable and allocated on each recomposition. It implements `create()` to build the node the first time, `update(node)` to copy new parameters into the existing node, and `equals` and `hashCode`. 3. **The factory**, `fun Modifier.x(...) = this then XElement(...)`, the public API. `update` runs only when the new element is **not equal** to the previous one at that position, which is why the element should be a `data class` or implement `equals` and `hashCode` by value. With instance equality every recomposition calls `update`, and the node is invalidated for nothing. ## Node lifecycle and invalidation - `onAttach()` runs when the node joins a layout in the UI tree; `onDetach()` when it leaves. A node can be detached and attached again. - `onReset()` runs when the node's layout is about to be recycled, for example an item scrolled out of a lazy list; reset item-specific state there. - `coroutineScope` is available between attach and detach and is **cancelled after `onDetach` returns**, so animations launched from `onAttach` stop with the node. - After `update`, the node is **automatically invalidated** for the phases its types touch: a `DrawModifierNode` redraws, a `LayoutModifierNode` re-measures. A complex node can override `shouldAutoInvalidate` to return `false` and call `invalidateDraw()` or `invalidateMeasurement()` itself, so a colour change does not cost a relayout. - To read a CompositionLocal, implement `CompositionLocalConsumerModifierNode` and call `currentValueOf(...)`. A read inside `draw` or `measure` is observed; a read elsewhere is not, unless the node implements `ObserverModifierNode` and wraps it in `observeReads`. ## Node types worth naming - `DrawModifierNode` draws into the layout's space through `ContentDrawScope.draw()`. - `LayoutModifierNode` changes how the wrapped content is measured and placed. - `PointerInputModifierNode` receives pointer events. - `SemanticsModifierNode` adds semantics for accessibility and testing. - `GlobalPositionAwareModifierNode` and `LayoutAwareModifierNode` receive position and size callbacks. - `DelegatingNode` composes several nodes into one; the documentation's example is a clickable node sharing interaction data between a focus node and an indication node. ## Pitfalls - Allocating a new node in `update` instead of mutating the existing one throws away the reuse the API exists for. - An element with a lambda or a mutable object as a property may never compare equal; decide which properties should trigger an update. - Writing a `@Composable` factory for something that does not need composition APIs pays the never-skipped cost on every recomposition. - Forgetting `this then ...` in the factory drops every modifier the caller chained before yours; always build on `this`. - Reaching for a node when chaining `graphicsLayer`, `drawBehind` or `layout` would do adds code the team must maintain for no gain.

  • In Compose, how does a Modifier.Node read a CompositionLocal such as LocalContentColor and react when it changes?
    Implement `CompositionLocalConsumerModifierNode` and call `currentValueOf(LocalContentColor)`. The value comes from where the modifier is used in the tree. A read inside `ContentDrawScope.draw()` or `MeasureScope.measure()` is observed, so the node redraws or re-measures on change; a read outside those scopes needs `ObserverModifierNode` with `observeReads { }` and an `onObservedReadsChanged()` override.
  • Why would a Modifier.Node override shouldAutoInvalidate to return false?
    Auto-invalidation re-runs every phase the node's types cover whenever `update` is called. A node that both measures and draws would relayout for a colour change. Returning `false` lets its update logic call `invalidateDraw()` when only the colour changed and `invalidateMeasurement()` only when the size changed, and nothing when only a click lambda changed.

  • Modifier.composed is deprecated and fails to compile in current Compose.
  • A ModifierNodeElement can rely on instance equality; Compose calls update only when needed anyway.
  • Creating a fresh node inside update is the safe way to apply new parameters.
  • A @Composable modifier factory is skipped like any other composable.
  • A Modifier.Node's coroutineScope keeps running after the node is detached.