What the Heck Is Jetpack Compose remember Vs remember mutableStateOf?

Arun Pandian M
Jetpack Composers
2 min readSep 28, 2022

--

Photo by Daniel Reche: https://www.pexels.com/photo/eggs-in-tray-on-white-surface-1556707/

Exists over time. This is what remember does.

Could change. This is what mutableStateOf does.

This blog is not about the finer details of mutable states and remember, so keep that in mind. There are two concepts that must be clarified before we begin..

1. Composition

A Composition is a tree-structure of the composables that describe your UI.

Initial composition is when a Composable tree gets rendered for the first time.

When Jetpack Compose runs your composables for the first time, during initial composition, it will keep track of the composables that you call to describe your UI in a Composition

2. Recomposition:

Recomposition is the process by which Jetpack Compose re-executes any composables that may have changed as a result of state changes and then updates the Composition to reflect any changes.

remember:

According to doc,

You can store immutable values when caching expensive UI operations, such as computing text formatting. The remembered value is stored in the Composition with the composable that called remember.

remember is a composable function that can be used to cache expensive operations.

Consider it a cache that is local to your composable.

It should be noted that you only need to use remember within composable functions (and the compiler will complain if you try to use it anywhere else).

There are other ways to store state besides composables.

Here, Because we used remember, clicking on the button will never update its text, implying that the value was set only during composition and cannot be changed (mutated).

remember {mutableStateOf} :

You can use the mutableStateOf function to create a mutable state.

We can change the randomNumber value by using mutableStateOf, which causes the Composable scope(s) that use it to recompose (Button content lambda, in this case)

With each Button click, the randomNumber value mutates, and as the state changes, recomposition and value changes in the Button Text.

I hope the difference is now clear.

I’ll see you in the next post.

Happy coding!

Buy me a coffee?
If you like this article, you can buy me a coffee. Thanks!

--

--

Arun Pandian M
Jetpack Composers

Senior Android developer at FundsIndia, A time investor to learn new things about Programming. Currently in a relationship with Green Bug(Android).