Skip to content

Instantly share code, notes, and snippets.

@shahzadansari
Created November 22, 2023 18:29
Show Gist options
  • Save shahzadansari/aba0434ba421a6eeefc533aab21c50fc to your computer and use it in GitHub Desktop.
Save shahzadansari/aba0434ba421a6eeefc533aab21c50fc to your computer and use it in GitHub Desktop.
Sample showing how logs can cause recompositions and how to fix them
@Composable
fun LogsCausingRecompositions() {
Box(modifier = Modifier.fillMaxSize()) {
var count by remember { mutableIntStateOf(0) }
Log.d("MyTag:", "Count: $count")
Button(
onClick = { count++ },
content = { Text("Increment") },
modifier = Modifier.align(Alignment.Center)
)
}
}
@Composable
fun Fixed() {
Box(modifier = Modifier.fillMaxSize()) {
var count by remember { mutableIntStateOf(0) }
SideEffect {
Log.d("MyTag:", "Count: $count")
}
Button(
onClick = { count++ },
content = { Text("Increment") },
modifier = Modifier.align(Alignment.Center)
)
}
}
@shahzadansari
Copy link
Author

Logs causing recompositions (when reading state)

Box(modifier = Modifier.fillMaxSize()) {
        var count by remember { mutableIntStateOf(0) }

        Log.d("MyTag:", "Count: $count")

        Button(
            onClick = { count++ },
            content = { Text("Increment") },
            modifier = Modifier.align(Alignment.Center)
        )
    }
logs-causing-recompositions.mov

@shahzadansari
Copy link
Author

Fix using SideEffect

Box(modifier = Modifier.fillMaxSize()) {
        var count by remember { mutableIntStateOf(0) }

        SideEffect {
            Log.d("MyTag:", "Count: $count")
        }

        Button(
            onClick = { count++ },
            content = { Text("Increment") },
            modifier = Modifier.align(Alignment.Center)
        )
    }
fix-logs-recompositions.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment