Android Nomad - #35 State
State in Compose
Comparison of remember, rememberSaveable, and derivedStateOf in Jetpack Compose.
1. remember
remember is used to preserve state across recompositions.
- Purpose: Stores a mutable state in the Composition.
- Lifecycle: Value is retained as long as the composable remains in the Composition.
- Use case: For storing simple state that doesn't need to survive configuration changes or process death.
Example:
var count by remember { mutableStateOf(0) }2. rememberSaveable
rememberSaveable is similar to remember, but it also preserves state across configuration changes and process death.
- Purpose: Stores a mutable state that survives configuration changes and process death.
- Lifecycle: Value is retained even if the app is killed and restored.
- Use case: For important UI state that should be restored if the user leaves and comes back to the app.
Example:
var text by rememberSaveable { mutableStateOf("") }3. derivedStateOf
derivedStateOf is used to create a state that's derived from other state objects.
- Purpose: Computes a value based on other state objects and caches the result.
- Lifecycle: Recalculated when any of the state objects it depends on changes.
- Use case: For values that are expensive to compute or need to be cached.
Example:
val sortedList by remember { derivedStateOf { originalList.sorted() } }Key Differences
1. Persistence:
- remember: Persists across recompositions.
- rememberSaveable: Persists across recompositions and configuration changes.
- derivedStateOf: Recalculates when dependencies change.
2. Usage:
- remember and rememberSaveable are used for storing state.
- derivedStateOf is used for computing derived state based on other state objects.
3. Performance:
- remember is lightweight.
- rememberSaveable has some overhead due to saving/restoring state.
- derivedStateOf can improve performance by caching complex calculations.
4. Scope:
- remember and rememberSaveable are typically used at the composable function level.
- derivedStateOf is often used within a remember block or in a ViewModel.
When to Use Each
- Use remember for simple, local UI state that doesn't need to survive configuration changes.
- Use rememberSaveable for important UI state that should persist across configuration changes and process death.
- Use derivedStateOf when you have a value that depends on other state and you want to optimize recomposition or cache expensive calculations.