Static Data vs Dynamic State
Data is any value that makes up the user interface (UI): it is the string displayed in a TextField, the function that is called when a Checkbox is clicked, even the subtle color changes when a Button is pressed is considered data.
Data that does not change is static. If all data in a UI is static and does not change, Compose will not update the UI after the first composition.
However, if you know the data is dynamic and want Compose to update the UI when it does change,
you must inform Compose by wrapping the data in a State.
Compose will then start observing the State for changes.
When the data changes, Compose will trigger a redraw of the UI, called a recomposition.
A recomposition simply re-runs the @Composable function,
which reads the new State and displays it in the UI.
In this example, Int data is upgraded to a MutableState by calling mutableStateOf(Int).
Click on both Buttons to see the difference.
Recomposition: area of effect
To make recompositions fast, not all @Composable functions are called;
sometimes only @Composable functions that read the updated State are re-run.
Remember, lambdas are functions too,
so even a trailing lambda like { Text("hello") } is a @Composable function.
This example shows how only lambdas that directly read updated State objects are re-run when recomposition occurs.
Notice how clicking on outerData resets innerData, but not the other way around,
showing you exactly where recomposition is happening.
Remembering State
To avoid resetting State across recompositions,
you can tell Compose to remember the State data between recompositions.
remember will run its lambda only during the first composition and cache its data in memory.
During a recomposition, remember will return the cached data instead of calling its lambda
again so the data is not reset. When the @Composable function's lifecycle ends,
the cache is automatically cleared.
The lambda can be considered the "constructor" or "initializer" of remember,
it only runs once.
In general, you should remember all your States as
recompositions can happen any time for any reason.
This example fixes the previous example to remember its State across recompositions.