Jetpack Compose Remember inside LazyColumn

ade sueb
2 min readJul 7, 2022

--

How to maintain remember (inside) Lazy Column, and not being destroyed after scroll back.

Well,, why I created story about Android? because this is who I am! Android and ML Engineer.

Remember

I will explain a little bit about remember. i hope this will help you.

Simple, if you have a state is in internal to a composable, then you can use remember.

In this example 1 is the value of the state that you want to maintain, the state can change it to 2 or another number in the future.

simply you can create inside compose function

// inside compose function
@Composable
fun ThisCompose() {
Column() {
var name by remember { mutableStateOf(1) }
}
}

and if you want to outside compose function, in this case outside Column()

// outside compose function
@Composable
fun ThisCompose() {
var name by remember { mutableStateOf(1) }
Column() {

}
}

Both of them works well and easy to maintain.

Remember inside Lazy column

But what if you want to use remember within the item inside lazy column?

actually you can simply just create inside LazyColumn,

// inside LazyColumn
@Composable
fun ThisCompose() {
LazyColumn(){
items( items = names ) { name ->
val state = remember{ mutableStateOf(1)
}
}
}

but.. remember inside lazy column will destroy and re-initiate when you scroll away from the item (until you can’t see the item) and scroll back to the item (see again).

Then,, how to remember the remember even you scroll awaayyy? :P

you must initiate the remember outside LazyColumn.

// outside LazyColumn
@Composable
fun ThisCompose() {
var name by remember { mutableStateOf(1) }

LazyColumn(){
items( items = names ) { name ->
}
}
}

rememberSaveable

or you can use rememberSaveable

// use rememberSaveable
@Composable
fun ThisCompose() {
LazyColumn(){
items( items = names ) { name ->
val state = rememberSaveable{ mutableStateOf(1)
}
}
}

what is this?

While remember helps you retain state across recompositions, the state is not retained across configuration changes. For this, you must use rememberSaveable. rememberSaveable automatically saves any value that can be saved in a Bundle.

not only retained across configuration or rotation changes but also retained from scroll away from the item.

--

--

ade sueb
ade sueb

Written by ade sueb

Still believe, can change the world with code..

Responses (1)