mutableStateOf vs derivedStateOf — Jetpack Compose
A small Compose concept that can make a big difference when managing state and recomposition.
mutableStateOf → stores state
Use it when your value is the source of truth and can be changed directly.var count by remember { mutableStateOf(0) }
Here, count is the actual UI state. When it changes, Compose can recompose the parts of the UI that read it.
derivedStateOf → derives state
Use it when you need to calculate a value from existing state.var count by remember { mutableStateOf(0) }
val isEven by remember {
derivedStateOf { count % 2 == 0 }
}
Now:
count→ source stateisEven→ derived stateisEvendoesn't need to be stored separatelyCompose tracks the states read inside the derived calculation
Simple rule ðŸ§
Storing a value? → mutableStateOf
Calculating a value from state? → derivedStateOf
One important point: derivedStateOf isn't something you should add to every calculated expression. It is most useful when the derived value changes less frequently than the inputs and you want to avoid unnecessary recompositions.
Understanding this distinction helps you write cleaner and more efficient Jetpack Compose code.
#Android #Kotlin #JetpackCompose #AndroidDevelopment #Compose #MobileDevelopment #KotlinTips

Post a Comment
Post a Comment