Compose State & Hoisting Interview Questions

UI › Compose Core

What is the difference between remember and rememberSaveable?

What a strong answer covers: remember keeps a value across recompositions but loses it when the composable leaves the composition or on configuration changes and process death. rememberSaveable also saves it in the saved instance state Bundle, so it survives rotation and process death, for types that fit in a Bundle or with a custom Saver. Use rememberSaveable for things like text field input or a selected tab.

What is state hoisting? Show a stateless and a stateful version of a composable.

What a strong answer covers: Hoisting moves state up to the caller and replaces it with a value parameter and an event callback: a stateless TextInput(value: String, onValueChange: (String) -> Unit), with a stateful wrapper that holds var text by rememberSaveable and passes it down. Stateless composables are reusable, previewable and testable, and state has a single source of truth. Hoist to the lowest common ancestor that needs it.

Where should state live: in a composable, a plain state holder class, or a ViewModel?

What a strong answer covers: UI element state only the UI cares about (expanded, scroll position, animation) lives in the composable or a plain state holder class remembered there, like rememberLazyListState. Screen-level state involving business logic or data (loaded items, form validation, loading and errors) lives in a ViewModel, which survives configuration changes and can be tested without UI. ViewModels shouldn't be passed down to low-level composables.

What is derivedStateOf, and when does it help versus hurt?

What a strong answer covers: derivedStateOf creates state computed from other state that only notifies readers when its result changes. It helps when the input changes much more often than the output, like val showButton by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }, so you recompose once instead of on every scroll pixel. It hurts when used for something that changes as often as its inputs (just compute it directly), and it must be wrapped in remember.

A screen's text field lags and loses characters while typing when its state lives in a ViewModel StateFlow. Why might that happen, and how do you fix it?

What a strong answer covers: Updating text through an asynchronous path (emitting to a StateFlow, debouncing, or doing work before updating) means the TextField sees a stale value for a frame and the input system and Compose state get out of sync, so the cursor jumps or characters are dropped. Fixes: hold the text in synchronous state (mutableStateOf in the ViewModel or composable, or TextFieldState with the newer BasicTextField) and update it immediately; run validation or search from a derived flow (snapshotFlow) separately.

Back to Compose State & Hoisting