Persisting and retrieving state
State is app data that may change over time. In a Compose app, state is typically represented as instances of State
or MutableState
. If such objects are used inside composable functions, a recomposition is triggered upon state changes. If a state is passed to several composables, all of them may be recomposed. This leads to the state hoisting principle: state is passed to composable functions rather than being remembered inside them.
Please note
Here, passed doesn’t necessarily mean using State<?>
or MutableState<?>
as parameters of composable functions. As you’ve seen in many of my examples, you can instead pass the current value of the state as an ordinary data type and the code that you want to be executed upon state changes as a callback.
Often, state is remembered in the composable that is the parent of the ones using the state. An alternative approach is to implement an architectural pattern called ViewModel....