JetpackCompose.app Home

Recomposition Highlighter

Author: Google Play

The Google Play team were among the first internal teams at Google to leverage Jetpack Compose. They worked very closely with the Compose team and even wrote a case study describing their experience migrating to Compose. One of the golden nuggets from that post was a Modifier that they developed to visualize recompositions.

Let's look at what it looks like in action. Our example has a simple composable function that has a button which increments a counter when its clicked. We are using the recomposeHighlighter modifier in two places - the root of the MyButtonComponent composable itself and the MyTextComponent composable which is a slot for the button itself.

@Composable
fun MyButtomComponent(
    modifier: Modifier = Modifier.recomposeHighlighter()
) {
    var counter by remember { mutableStateOf(0) }

    OutlinedButton(
        onClick = { counter++ },
        modifier = modifier,
    ) {
        MyTextComponent(
            text = "Counter: $counter",
            modifier = Modifier.clickable {
                counter++
            },
        )
    }
}

@Composable
fun MyTextComponent(
    text: String,
    modifier: Modifier = Modifier,
) {
    Text(
        text = text,
        modifier = modifier
            .padding(32.dp)
            .recomposeHighlighter(),
    )
}

On running this example, we notice that the button and the text inside the button both have a blue bounding box initially. This makes sense as that's the first composition and it corresponds to the two places where we are using the recomposeHighlighter() Modifier. When we click on the button, we notice the bounding box only around the text inside the button and not the button itself. This is because Compose is smart about recompositions and it doesn't need to recompose the entire button - just the composable that depends on the counter value that was updated.

Recompose highlighter demo

recomposeHighlighter Modifier in action

Using this modifier, we were able to visualize how recompositions are happening in our Composable functions. This is a really powerful tool and I can imagine this being extended in really creative ways.

Have a project you'd like to submit? Fill this form, will ya!

JetpackCompose.app Job Board

Find the best Android jobs in world-class companies. Here are some featured jobs from the job board