One Off the Slack: Z-Stacking?

Guy Bieber asked:

I have a colleague who zstacks all their screens and changes what is in front. I typically just switch what is being rendered in a composable with a if or case statement. Is doing stacking a best practice for compose?

Long-term, this sort of concern should be handled by navigation frameworks, including Jetpack’s own Navigation component. In the short term (hopefully measured in weeks), we have to worry about this sort of thing ourselves. And so the question is: do you change elevation (“zstack”) to control what is in front, or do you avoid rendering non-visible content in the first place?

According to Google’s Alexandre Elias, the answer is the latter:

if/case statements are the recommended best practice for Compose. that is what we are using in all our sample apps and optimizing Compose’s performance for

After all, why render nodes that the user will not see?

Alexandre pointed out a possible reason why somebody might try the elevation approach:

if the idea behind the zstacking approach is to cache/preload expensive data for performance reasons, the best practice would be to hoist up that state to a parent Composable of the screens so that it’s remembered even if the child screen falls into an “else” block

That’s one of the many differences between the classic View system and Compose. With views, we might want to pre-create the widgets even if they are not yet visible, so that they are ready when we need them. ViewPager and ViewPager2, for example, will set up enough pages to allow for animated transitions between them. Compose is much more of a “just in time” system, where you only define the UI nodes that you really need right now, based on the current state.

And, as Alexandre notes, playing elevation games might make things worse:

Compose doesn’t have much in the way of optimizations to avoid doing unnecessary work for z-occluded composables, so having tons of stacked invisible screens could cause more performance problems than it solves


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!