Peppe L-G
Peppe L-G

Reputation: 8345

Unnecessary recompositions are triggered in Jetpack Compose

I have the following Android Jetpack Compose component:

@Composable
fun TestScreen(){

    println("inside-TestScreen()")
    
    var number by remember{ mutableStateOf(1) }

    Button(onClick = { number++ }) {

        println("inside-Button()")
        
        Column {

            println("inside-Column()")
            
            Text("Hello $number")

        }

    }

}

When it's composed, the following is logged:

inside-TestScreen()
inside-Button()
inside-Column()

This works as I expect. However, when I click on the Button (i.e. changes the state variable number), a recomposition happens, and the following is logged:

inside-Button()
inside-Column()

Apparently, the Button content is recomposed, and I don't understand why. The Button content does not use the number variable, so I thought Jetpack Compose would be smart enough to understand that the Button content wouldn't need to recompose. I thought only the Column content would recompose, and only inside-Column() would be logged.

Why does the content of the Button recompose even though it has no dependency on a state that changed?

Upvotes: 1

Views: 1472

Answers (1)

Thracian
Thracian

Reputation: 67149

Because Column, Box, Row and any Composable that is inline and returns Unit does not create a scope. When recomposition happens Jetpack Compose checks out closest scope to recompose which is content of Button in your exmple.

You can refer these answers for more details and the articles in first link.

Jetpack Compose Smart Recomposition

Why does mutableStateOf without remember work sometimes?

Upvotes: 4

Related Questions