1

Here's an example:

@Composable
fun MyList(items: List<Item>) {
    val lazyListState = rememberLazyListState()

    lazyListState.layoutInfo // Accessing this field causes MyList to recompose infinitely

    LazyColumn(state = lazyListState) {
        itemsIndexed(items) { _, item ->
            MyItem(item)
        }
    }
}

Why does accessing layoutInfo causes MyList to recompose infinitely? What am I doing wrong here?

Ahmad Hamwi
  • 204
  • 2
  • 10

1 Answers1

2

You should use it inside derivedStateOf to react when any state you read changes frequently, especially more than recomposition or to cause recomposition on each frame when you read from it

val myState = remember { derivedStateOf { lazyListState.lazyLayoutInfo // access properties} }

as you can see in warning in

enter image description here

Also another option android studio suggest is to use SnapshotFlow as

LaunchedEffect(lazyListState) {
        snapshotFlow { lazyListState.layoutInfo }
            .collect { TODO("Collect the state") }
    } 

You can check out Jetpack Compose — When should I use derivedStateOf? article from Ben Trengrove

Thracian
  • 43,021
  • 16
  • 133
  • 222
  • Thank you for your detailed explanation and the blog post. This is exactly what I needed to learn more about the problem. But the warning does not appear for me for some reason, do you know how to enable it? – Ahmad Hamwi Jan 14 '23 at 13:52
  • @AhmadHamwi i don't know why it's disabled, i have never encountered this problem. I always see warnings. And if you think this answer is detailed you should see [this one](https://stackoverflow.com/questions/65779226/android-jetpack-compose-width-height-size-modifier-vs-requiredwidth-requir/73316247#73316247=. I normally write long detailed answer but this one is brief and suggested by Android Studio as well – Thracian Jan 14 '23 at 13:59
  • No problem, I will look more into the warning issue, I might not have asked this question here if the warning was visibile for me :"). And well done on your dedication! You're a true hero for the stackoverflow community. I'm marking your answer as Accepted as it's clearly answers my question, especially where the article explains it in detail. – Ahmad Hamwi Jan 14 '23 at 14:07