On my screen I have MyTopItem() and below list with items. When I'm starting scrolling my list I want to hide MyTopItem().

It works fine but scrolling is so laggy. It happens because during scrolling all items in MyLazyVerticalGridItemsSection() recompose.

How can I avoid recomposing during scrolling?

Column(Modifier.fillMaxSize()) {
    val listState = rememberLazyListState()

    AnimatedVisibility(
        visible = listState.firstVisibleItemScrollOffset < 1,
        enter = expandVertically(),
        exit = shrinkVertically()
    ) {
        MyTopItem()
    }
    MyLazyVerticalGridItemsSection(
        items = myItems,
        listState = listState
    )
}

Solution 1:

This happens because you're using listState.firstVisibleItemScrollOffset directly, so each time this value changes, the recomposition is triggered.

In such cases derivedStateOf should be used - it will only trigger recomposition when the result of the calculation changes::

val visible by derivedStateOf { listState.firstVisibleItemScrollOffset < 1 }