https://kotlinlang.org logo
Title
p

Peter Mandeljc

02/21/2023, 10:03 AM
Does the position, where you call
remember
, matter? Should 2nd code be preferred?
// 1st example
var shouldShowOnboarding by remember { mutableStateOf(true) }
Surface(modifier) {
    if (shouldShowOnboarding) {
        OnboardingScreen()
    } else {
        Greetings()
    }
}

// 2nd example
Surface(modifier) {
    var shouldShowOnboarding by remember { mutableStateOf(true) }
    if (shouldShowOnboarding) {
        OnboardingScreen()
    } else {
        Greetings()
    }
}
I guess performance wise, it won't matter much, since Surface will not get recomposed. But I'm still wondering.
c

Csaba Szugyiczki

02/21/2023, 10:16 AM
As a rule of thumb, you should create these state variables on the lowest level possible. If you do not want to change the value of
shouldShowOnboarding
from a higher level then do not hoist it, leave it as close to the usage point as possible.
So yes, I would go with the second variant of this example
p

Peter Mandeljc

02/21/2023, 10:17 AM
I guess you mean that only from code readability perspective?
c

Csaba Szugyiczki

02/21/2023, 10:19 AM
Yes, readability and cleanliness. I don’t think it would have performance or any other penalties to have it higher within the same Composable function
p

Peter Mandeljc

02/21/2023, 10:22 AM
yeah, I strongly agree with that. But still, I guess by doing 1st example, compose has to do a bit more checks, if Surface needs to be re-composed? Not worried about performance, just to satisfy my curiosity 🙂
c

Csaba Szugyiczki

02/21/2023, 10:27 AM
I think that would be true only if
shouldShowOnboarding
was a parameter of Surface
p

Peter Mandeljc

02/21/2023, 11:31 AM
thanks for info! 🙂
c

Csaba Szugyiczki

02/21/2023, 12:13 PM
No problem! 🙂