I have ```val listState = rememberLazyListState()`...
# compose-desktop
b
I have
Copy code
val listState = rememberLazyListState()
and I use it with
LazyColumn
and it works fine: composable function is executed once. The problem is when I try to check visible elements, and I call
listState.layoutInfo
. Then composable function is recalled (state was changed?) and view is regenerated. Why?
a
Can you post a short example?
b
a
Not sure I understand the problem. That’s how state in compose works. Whenever you read a state value inside a @Composable function and that state changes, the function will get called to (re)create the UI. (this all roughly-speaking, the details are somewhat more complex).
b
Yup! Keyword: "*read* a state" 🙂 State is not modified, I just want to check if element is visible or not. But it causes recalling whole function, and few times bigger CPU usage.
a
That state is modified during layout
Not by you
If you want your UI to depend on a function of the state whose output changes less frequently than the state itself, look into derivedState.
b
Like this?
Copy code
val listState by remember { derivedStateOf { LazyListState() } }
If yes, then it doesn't help.
a
No, not like that. Define the list state normally
But then say you want to show the number of visible items. Use val itemCount by derivedStateOf { listState.layoutInfo.visibleItems.size }
Then the code that reads itemCount will only be called when the value of itemCount changes, instead of whenever layoutInfo changes
and, just for future questions, this is more appropriate for the general #compose channel, since it’s not specifically about compose on the desktop.
b
I wasn't sure it is problem of Desktop itself 🙂
Anyway: with derived state,
List()
is called twice, what is good for me 🙂 Thanks a lot for help and explanation :-)
a
You’re welcome. Also, don’t worry about extra recompositions too much unless they’re causing a measurable problem for you.
That’s the guideline anyway.
b
Right, it is not problem for me when function is called twice (in this example with visible items equals
0
and
6
). Problem is when function is called in infinite loop, because of wrong way of reading visible items size 🙂