Understanding State, Mutable State, remember, and rememberSaveable in JetpackCompose
State and Mutable State:
State is like the information you want to remember or keep track of in your daily life. It could be something as simple as the number of items you have in your shopping cart or the current temperature outside.
Mutable State refers to the ability to change or update this information. Imagine having a whiteboard where you write down the number of items in your shopping cart, and you can easily erase and update that number.
In Compose, mutableStateOf is like having that whiteboard. It allows you to create a variable that can be updated, and when it changes, it triggers a reevaluation of your Compose UI.
Remember:
Now, let's introduce the concept of remember. In your daily life, you have things you want to remember even if you momentarily forget them. For example, you might want to remember your friend's birthday or an important appointment.
In Compose, remember is like a tool that helps you remember values across recompositions (UI updates). It's useful for keeping track of information that should persist even when your UI is being re-rendered.
var count by remember { mutableStateOf(0) }
Here, count is your remembered value, and remember is the tool that helps Compose remember the value of count even if the UI is recomposed.
RememberSaveable:
Now, let's consider the scenario where you want to remember something important even if there are significant changes around you. For instance, you want to remember your friend's birthday even if you switch to a new calendar app.
In Compose, rememberSaveable is like an advanced tool that not only helps you remember values but also survives certain changes, such as screen rotations or configuration alterations.
var countSaveable by rememberSaveable { mutableStateOf(0) }
Here, countSaveable is your remembered value, and rememberSaveable is the tool that helps Compose remember the value of countSaveable even if there are changes in the environment.
Layman's Example:
Imagine you're managing a shopping cart in an app:
In this analogy, your shopping cart is your state, the ability to add or remove items is your mutable state, and the magical tools represent remember and rememberSaveable – helping you retain information across different situations.