Compose: remember() with keys vs. derivedStateOf()

derivedStateOf {} is used when your state or key is changing more than you want to update your UI. It acts as a buffer for you, buffering out the changes you don’t need. That is the primary difference between a keyed remember {} and derivedStateOf {}. With remember {}, you will still recompose as much as your key changes, which isn’t a bad thing if that’s what you need. If you don’t need those recompositions though, that is where derivedStateOf {} comes in.

Take for example showing a button only if the user has scrolled a LazyColumn.

val isVisible = lazyListState.firstVisibleItemIndex > 0

firstVisibleItemIndex will change 0, 1, 2 etc as the user scrolls and cause a recomposition for every time it changes.

I only care about if it’s 0 or not 0 and only want to recompose when that condition changes.

derivedStateOf is my buffer, it’s buffering out all of those extra state changes I don’t need and limiting the recomposition to only when the derivedStateOf changes.

val isVisible = remember { derivedStateOf { lazyListState.firstVisibleItemIndex > 0 } }

For the example given in the question, a remember(key1, key2) {} is the correct API to use there, not derivedStateOf {} because you want your UI to update any time the key changes, there isn’t any change to buffer out.

Update: There is a detailed explanation of derivedStateOf in this talk https://www.youtube.com/watch?v=ahXLwg2JYpc&t=412s

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)