I'm reading <Thinking in Compose> and have some qu...
# compose
e
I'm reading Thinking in Compose and have some questions about this part:
In Compose, you call the composable function again with new data. Doing so causes the function to be recomposed--the widgets emitted by the function are redrawn, if necessary, with new data. The Compose framework can intelligently recompose only the components that changed.
For example, consider this composable function which displays a button:
```@Composable
fun ClickCounter(clicks: Int, onClick: () -> Unit) {
Button(onClick = onClick) {
Text("I've been clicked $clicks times")
}
}```
Every time the button is clicked, the caller updates the value of
clicks
.
I don't understand why the last sentence is true. We don't see the
onClick
function. Are we supposed to infer that it is
() -> clicks++
and that
clicks
is bound to the parameter?
b
That sentence isn't saying that is what always happens. The "caller" is whoever is calling this code, not the code from the example. That sentence is true because it is telling you that is what is happening.
The point to understand I guess is that nothing will happen unless the caller updates whatever value they are passing into "clicks" and that is what causes the recomposition
e
Thanks for replying, @Ben Trengrove [G]. What's confusing me is that I don't see why clicking on the button causes
ClickCounter
to be called again. Are you saying that the
onClick
method calls
ClickCounter
?
If there were another button whose
onClick
method called
ClickCounter()
, I'd understand.
b
Clicking on the button won't cause ClickCounter to be called again. That relys on the caller updating some compose state in order to change it, that compose state being used for "clicks" is what will end up causing ClickCounter to be called again via recomposition. It will end up looking like this
Copy code
@Composable
fun MyScreen() {
   var clickCount by remember { mutableStateOf(0) }
   ClickCounter(clickCount, onClick = { clickCount ++ })
}
e
I understand the code you provided. Are you saying that's how
ClickCounter
might be called?
b
Yeah, it's just one way it could be. "Every time the button is clicked, the caller updates the value of clicks" is saying the caller is doing this. If for instance the onClick was empty, nothing would change
e
Thanks so much, @Ben Trengrove [G].