Leila_ygb
Leila_ygb

Reputation: 91

Preformance in jetpackCompose

As you can see in the code, I have two composable functions named Screen and Body. When the state of the showError changes, the body function is also recompose. Does it have any side effect? If yes, how to avoid this recompose.

    @Composable
    fun Screen(viewModel: ViewModel) {
        val state by viewModel.uiState.collectAsState()
        if (state.showError) {
            Text("sample view")
        }
        Body(state = state)
    }

    @Composable
    fun Body(state: UiState) {
     // todo
    }

Upvotes: 1

Views: 56

Answers (1)

Ahsan Zia
Ahsan Zia

Reputation: 106

This is the default behaviour of the compose function. Whenever a state is observed due to any change in state value, the function recomposes and displays the updated values. So, yeah there are things that you may need to make sure when using the composable functions like for example, if you are declaring a variable in a composable function and that variable is later updated then that variable's value will go in default state when function is recomposed.

To avoid recomposition: I do not think that is possible specially when you are using state variables or remember functions but what you can do is minimise the recompositions needed.

Below is a reference on how its lifecycle works.

https://developer.android.com/jetpack/compose/lifecycle

Upvotes: 1

Related Questions