DEV Community

Javad Vatan
Javad Vatan

Posted on

Why doesn't dimensionResource in Jetpack Compose use remember, and what happens if we add it?

In Jetpack Compose, we use **dimensionResource **to retrieve a dimension value from resources and convert it to Dp. The built-in function is defined as:

@Composable
@ReadOnlyComposable
fun dimensionResource(@DimenRes id: Int): Dp {
val context = LocalContext.current
val density = LocalDensity.current
val pxValue = context.resources.getDimension(id)
return Dp(pxValue / density.density)
}

This function does not use remember.

My questions:

  1. Why doesn't dimensionResource internally use remember to cache the
    result and prevent redundant recomputation during recomposition?

  2. What would happen if I wrapped it in remember like this?

@Composable
fun rememberedDimensionResource(@DimenRes id: Int): Dp {
val context = LocalContext.current
val density = LocalDensity.current
return remember(id) {
val pxValue = context.resources.getDimension(id)
Dp(pxValue / density.density)
}
}

Would this improve performance by avoiding unnecessary resource lookups, or is there a reason why dimensionResource is designed without remember?

I'm trying to understand the implications of caching dimension values in Jetpack Compose and whether this would provide a real optimization.

Any insights would be greatly appreciated.

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs