Compose State & Hoisting Flashcards
UI › Compose Core
- What does mutableStateOf return, and why does writing to it trigger recomposition?
- It returns an observable MutableState<T>. The Compose snapshot system records which composables read .value, so any write to .value schedules recomposition of exactly those readers.
- Why must mutableStateOf be wrapped in remember inside a composable?
- Without remember, a fresh MutableState is created on every recomposition, resetting the value. remember stores the object in the Composition so the same state is returned across recompositions.
- Difference between remember and rememberSaveable?
- Both survive recomposition. remember is lost on activity/process recreation (e.g. rotation). rememberSaveable also persists across config changes and system-initiated process death via saved instance state, but not when the user fully dismisses the activity.
- How do you store a custom type in rememberSaveable?
- Anything that fits in a Bundle works automatically. For custom types, make it @Parcelize Parcelable, or supply a custom Saver via mapSaver or listSaver passed as the stateSaver argument.
- What is state hoisting and what is the standard signature it produces?
- Moving state up to a caller so a composable becomes stateless. The pattern is value: T (state down) plus onValueChange: (T) -> Unit (events up), making the composable reusable, testable, and giving a single source of truth.
- State that hoisting follows: name the three rules for where to hoist.
- Hoist to at least the lowest common parent of all composables that read it; to at least the highest level it may be changed; and if two states change in response to the same events, hoist them together.
- What is derivedStateOf and when should you use it?
- It creates a State computed from other state reads, recomputing only when inputs change and notifying readers only when the result changes. Use it when frequently-changing inputs map to a result that changes far less often (e.g. scrollOffset > 0 to show a button).
- Why is using mutableListOf() or ArrayList directly as Compose state a bug?
- They are not observable, so mutating them does not trigger recomposition and the UI shows stale data. Use mutableStateListOf/mutableStateMapOf, or hold an immutable List in a MutableState.
- When should state live in a ViewModel versus a plain state holder remembered in the composable?
- ViewModel for screen-level UI state and business logic: it survives config changes and is scoped to a ViewModelStoreOwner. A plain remembered class for pure UI logic/element state tied to the Composition lifecycle, needing no business logic.