Pass by Value vs CompositionLocal vs Static CompositionLocal
Examples to show how to pass data to composable functions using function parameters(i.e. pass by value), CompositionLocal and static CompositionLocal
There are a few ways you can pass data to a composable function:
- Pass by Value (function parameter)
- CompositionLocal
- Static CompositionLocal
Pass by Value is a conventional way. CompositionLocal and static CompositionLocal is a Jetpack Compose way, but static CompositionLocal is useless in my opinion (will be explained later).
Pass by Value
This is a very simple example to pass counter
value to the Parent()
composable function, then increments it by 1 and passes it to the Child()
composable function. Finally, it calls the GrandChild()
composable function without any parameters.
Let’s investigate the code, what do you think the Logcat outputs are during the first composition and the subsequent recomposition?
private val tag = "CompLocal"
@Composable
fun PassByValueDemo() {
var counter by remember {
mutableStateOf(-1)
}
MyButton(onClick = { ++counter }, text =…