Jetpack Compose derivedStateOf function
Let's say we have a LazyColumn with many items. We are going to show a FAB whenever you scroll in the list after you pass the first item in the list. Clicking on the FAB takes you to the first element of the list. We only will show FAB if the first item is not showing.
One solution can be to check the firstVisibleItemIndex of the LazyColumn state:
This code will work! But what's wrong with that? If we scroll the list the listState will changes and forces the recomposition multiple times. After listState.firstVisibleItemIndex > 0 we know that showButton value is true and there is no need to recomostion because of scrolling. In fact the showButton will remains true until we see the first element of the list again. What should we do?
derivedStateOf came to rescue. Using this function guarantees that the calculation will only occur whenever the result in the block of derivedStateOf changes. In the code above, for example, if firstVisibleItemIndex is 10 and then we scroll more and firstVisibleItemIndex changes to 11, showButton will not changed and remains true but recomposition will occurs. Recomposion only should be occurs once we scroll to top and see the first element in the list. But in the following code, recomposition only will occurs when the value inside of the derivedStateOf block really changes.
This code will minimize unnecessary recompositions: