skip to content

In Jetpack Compose, when you expose a custom spacing scale or brand colors through a CompositionLocal, how do you choose compositionLocalOf or staticCompositionLocalOf?

level: seniorimportance: should knowfreq 40%

answer

  1. tracked vs untracked reads
  2. what a change invalidates
  3. how often the value changes
  4. default factory and equality policy

basics

~20 s

compositionLocalOf tracks reads, so a new value recomposes only readers of current; staticCompositionLocalOf does not, so a change recomposes the provider's whole content. Use static for values that almost never change, such as a spacing scale, and compositionLocalOf for colors that change or animate.

solid answer

~40 s

Both create a `ProvidableCompositionLocal` you provide with `CompositionLocalProvider(LocalX provides value)` and read with `LocalX.current`. With `compositionLocalOf`, reads are tracked: a new value invalidates only the composables that read `current`, and its default `structuralEqualityPolicy()` ignores a new but equal value. With `staticCompositionLocalOf`, reads are not tracked, which is cheaper per read, but changing the value recomposes the entire `content` lambda of the provider. So a fixed spacing scale read in hundreds of places suits `staticCompositionLocalOf`; semantic colors that animate between themes suit `compositionLocalOf`. For a rare dark or light toggle either works. Give each key a sensible default factory, mark token classes `@Immutable`, and expose them through an object with `@Composable` getters.

code

kotlin · 31 lines
kotlin
@Immutable
data class BankSpacing(val small: Dp = 8.dp, val medium: Dp = 16.dp, val large: Dp = 24.dp)

@Immutable
data class BankColors(val positiveAmount: Color, val negativeAmount: Color)

val LocalBankSpacing = staticCompositionLocalOf { BankSpacing() }
val LocalBankColors = compositionLocalOf {
    BankColors(positiveAmount = Color.Unspecified, negativeAmount = Color.Unspecified)
}

private val DefaultSpacing = BankSpacing()
private val LightBankColors = BankColors(Color(0xFF1B6E2E), Color(0xFFB3261E))
private val DarkBankColors = BankColors(Color(0xFF8BD89A), Color(0xFFF2B8B5))

object BankTokens {
    val spacing: BankSpacing
        @Composable @ReadOnlyComposable get() = LocalBankSpacing.current
    val colors: BankColors
        @Composable @ReadOnlyComposable get() = LocalBankColors.current
}

@Composable
fun BankTokensProvider(darkTheme: Boolean, content: @Composable () -> Unit) {
    CompositionLocalProvider(
        LocalBankSpacing provides DefaultSpacing,
        LocalBankColors provides if (darkTheme) DarkBankColors else LightBankColors,
    ) {
        MaterialTheme(content = content)
    }
}

go deeper

for a junior

Recall that a CompositionLocal is provided with CompositionLocalProvider and read with current, and that compositionLocalOf and staticCompositionLocalOf create one.

for a middle

Explain tracked versus untracked reads and what each factory recomposes when the provided value changes.

for a senior

Pick the factory from how often the value changes, set sensible defaults, use @Immutable token classes, and avoid implicit dependencies that hide data flow.

for a principal

Set the design-system convention: which tokens are static, which are tracked, who may re-provide them, and how screens access them.

## Why custom tokens go in a `CompositionLocal` Material 3's `ColorScheme`, `Typography` and `Shapes` have fixed fields. A banking app usually needs more: a spacing scale (`small`, `medium`, `large`), semantic colors such as a positive-amount green and a negative-amount red, perhaps an elevation set. Jetpack Compose's answer is the same mechanism `MaterialTheme` itself uses: a **`CompositionLocal`**, a key whose value is provided by an ancestor and read anywhere below through `.current`. The usual shape, from the Android guide to custom design systems: 1. An `@Immutable` data class per token set, so the Compose compiler treats it as stable. 2. A top-level key created with `compositionLocalOf { ... }` or `staticCompositionLocalOf { ... }`, whose lambda is the **default factory**. 3. A theme composable that calls `CompositionLocalProvider(LocalBankSpacing provides spacing, ...)` and then `MaterialTheme(...)` inside it. 4. An object (`BankTokens.spacing`, `BankTokens.colors`) with `@Composable` getters that return `LocalX.current`, mirroring `MaterialTheme.colorScheme`. ## The two factories | | `compositionLocalOf` | `staticCompositionLocalOf` | |---|---|---| | Are reads tracked? | yes, each reader of `.current` is recorded | no | | When the provided value changes | only composables that read `.current` are invalidated | the **entire `content` lambda** of the provider recomposes | | Change detection | a `SnapshotMutationPolicy`, by default `structuralEqualityPolicy()` (an equal value is no change) | no policy parameter | | Best for | values that change or animate: colors in a theme transition | values that rarely or never change: a spacing scale, a `Context`, a font loader | The runtime's own KDoc gives the rule of thumb: values that are highly unlikely to change, such as the Android context or font loaders, should consider `staticCompositionLocalOf`; "a color, or other theme like value, might change or even be animated", so `compositionLocalOf` fits. The custom-design-system guide's samples nevertheless use `staticCompositionLocalOf` for extended colors, and that is reasonable when the only change is a rare dark or light switch: recomposing the provider's content once on that switch can be an acceptable price for untracked reads everywhere else. ## Choosing for a banking app - **Spacing scale**: fixed for the app's lifetime, read in hundreds of places. `staticCompositionLocalOf` avoids per-read tracking and costs a full recomposition only if you ever provide a new scale. - **Semantic colors that follow dark theme**: either works for a toggle; choose `compositionLocalOf` if you animate between themes, because a static local would recompose the entire subtree on every animation frame. - **Anything that changes often** (a value driven by scroll or by user input) usually does not belong in a `CompositionLocal` at all; pass it as a parameter or read state lower down. ```kotlin @Immutable data class BankSpacing(val small: Dp = 8.dp, val medium: Dp = 16.dp, val large: Dp = 24.dp) @Immutable data class BankColors(val positiveAmount: Color, val negativeAmount: Color) val LocalBankSpacing = staticCompositionLocalOf { BankSpacing() } val LocalBankColors = compositionLocalOf { BankColors(positiveAmount = Color.Unspecified, negativeAmount = Color.Unspecified) } ``` ## Defaults, visibility and misuse - **Default factory.** It runs when no ancestor provides a value. The KDoc suggests throwing an exception if no reasonable default exists; the guide warns that without a default every preview and test must provide the value. `Color.Unspecified` and `TextStyle.Default` are the conventional neutral defaults. - **Visibility.** Expose the key as `ProvidableCompositionLocal` only where re-providing is allowed; typed as `CompositionLocal`, it can be read with `.current` but not provided. - **Equality.** Because `compositionLocalOf` defaults to structural equality, creating a new but equal `BankColors` instance on each recomposition of the theme function does not invalidate readers. A class without a meaningful `equals` loses that protection. - **Nesting.** Providers nest like `MaterialTheme`: the innermost value wins for its subtree, so a dense statement table can provide a tighter spacing scale without affecting the rest of the screen. - **Scope.** The guide warns against overuse: a `CompositionLocal` makes dependencies implicit. Tokens that any descendant may need are a good fit; a screen's `ViewModel` is not. ## What a senior answer shows That you know what each factory invalidates, can tie the choice to how often the value changes, and can name the costs of the default factory and of implicit dependencies, rather than reaching for one factory by habit.

  • What should a CompositionLocal's default factory return when no ancestor provides a value?
    A neutral but usable value such as `Color.Unspecified`, `TextStyle.Default` or a default token instance, so previews and tests work without setup. The runtime KDoc says that if no reasonable default exists you can throw an exception, at the cost of forcing every preview and test to provide the value.
  • Why might a team expose a token key as CompositionLocal rather than ProvidableCompositionLocal?
    Typed as `CompositionLocal`, the key can still be read with `.current` but cannot be used in `provides`, so only the design-system module that holds the providable reference can set it. That stops screens from quietly overriding tokens for a subtree.
  • Is a CompositionLocal the right place for a screen's ViewModel?
    No. The Android guide calls this a bad practice: not every descendant needs it, and it hides the dependency. Pass composables only the data and event lambdas they need; keep composition locals for tree-wide values such as theme tokens.

  • staticCompositionLocalOf recomposes only the composables that read its current value.
  • compositionLocalOf invalidates readers even when the new value equals the old one.
  • Animated theme colors belong in a staticCompositionLocalOf for performance.
  • A CompositionLocal needs no default because the theme always provides it.
  • Any frequently changing state should be shared through a CompositionLocal.