DEV Community

myougaTheAxo
myougaTheAxo

Posted on

CompositionLocal: Sharing Data Across the Compose Tree

CompositionLocal enables efficient, implicit data sharing throughout your Compose hierarchy without prop drilling.

Creating a CompositionLocal

// Define CompositionLocal
val LocalThemeColors = compositionLocalOf {
    ThemeColors(
        primary = Color.Blue,
        secondary = Color.Green
    )
}

data class ThemeColors(
    val primary: Color,
    val secondary: Color
)

// Provide values
@Composable
fun MyApp() {
    CompositionLocalProvider(
        LocalThemeColors provides ThemeColors(
            primary = Color.Red,
            secondary = Color.Yellow
        )
    ) {
        MyScreen()
    }
}

// Consume values
@Composable
fun MyButton() {
    val colors = LocalThemeColors.current
    Button(
        colors = ButtonDefaults.buttonColors(
            containerColor = colors.primary
        ),
        onClick = {}
    ) {
        Text("Click")
    }
}
Enter fullscreen mode Exit fullscreen mode

Static CompositionLocal

For values that never change:

val LocalUserInfo = staticCompositionLocalOf {
    UserInfo(name = "Guest", id = "0")
}

data class UserInfo(val name: String, val id: String)
Enter fullscreen mode Exit fullscreen mode

Nested Providers

Override values in subtrees:

@Composable
fun MainContent() {
    CompositionLocalProvider(
        LocalThemeColors provides baseTheme
    ) {
        Row {
            LeftPanel()
            CompositionLocalProvider(
                LocalThemeColors provides darkTheme
            ) {
                RightPanel()
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

CompositionLocal is perfect for theming, user context, and other ambient data.


8 Android app templates available on Gumroad

Top comments (0)