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?
CodePudding user response:
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
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