Skip to content

Conversation

@ivk1800
Copy link

@ivk1800 ivk1800 commented Sep 20, 2025

What I have done and why

I refactored the SearchRoute → SearchScreen → SearchToolbar → SearchTextField chain to reduce unnecessary recompositions when the search query changes.

Before: entering a search query triggered recomposition of
SearchRoute, SearchScreen, SearchToolbar, SearchTextField, EmptySearchResultBody, RecentSearchesBody.

After: only SearchTextField and EmptySearchResultBody are recomposed.
SearchRoute, SearchScreen, and SearchToolbar stay stable.

This was achieved by:

  1. Passing State instead of raw String as a parameter down the composable chain.
  2. Adapting previews accordingly.

The approach is similar to this recomposition visualization(before) and this one (after).
In the "before" example, intermediate functions get recomposed unnecessarily because they take a changing value as a parameter. In the "after" example, they take a stable lambda, so only the leaf node (RedBox) is recomposed.

Why:

  1. Reduces the number of recompositions.
  2. Improves performance by keeping intermediate composables stable.

I followed the official Compose best practice — “Defer reads as long as possible” (see Android Performance Best Practices) — by deferring access to changing data until it’s needed, thus avoiding unnecessary recompositions.

@ivk1800 ivk1800 requested a review from dturner as a code owner September 20, 2025 18:50
@hoangchungk53qx1
Copy link
Contributor

Better yet, don't expect States in you components. Expect the final value as a parameter

@hoangchungk53qx1
Copy link
Contributor

Every time you read state in a Composable, you're creating a subscription. That Composable will recompose whenever that state changes. Read state too early in your composition tree, and you might be triggering unnecessary recompositions across large portions of your UI.

internal fun SearchScreen(
modifier: Modifier = Modifier,
searchQuery: String = "",
searchQueryState: State<String> = remember { mutableStateOf("") },
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bad practice for passing State objects as parameter
Deffer state in compose by lambda

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants