Ahmad Hamwi
Ahmad Hamwi

Reputation: 343

Accessing layoutInfo field from LazyListState causes the enclosing composable to recompose infinitely

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?

Upvotes: 1

Views: 579

Answers (1)

Thracian
Thracian

Reputation: 67433

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

Upvotes: 2

Related Questions