DEV Community

Kumar Rishi
Kumar Rishi

Posted on

1

Jetpack Compose -Difference between mutableStateOf() and derivedStateOf()

Image description

Hey Guys!!, Well thought of sharing my experience on those concepts, which might gets overlooked quite frequently.
Have You ever wondered the exact usecase of mutableStateOf() and derivedStateOf()

Let's say when you have some variable and you want to trigger an UI change basically recomposition , when that variable changes, most likely you will use mutableStateOf()



val count = mutableStateOf(1)


Enter fullscreen mode Exit fullscreen mode

However to make sure recomposition value must be stored you need to use remember, maybe next time i will focus on this

Now think of a situation, where you are storing some value, on that value change you automatically want to modify other variable, then derivedStateOf() is preferable
for ex :-



val height by remember{ mutableStateOf(10) }
val width by remember{ mutableStateOf(10) }
val area by remember{ derivedStateOf(height * width) }



Enter fullscreen mode Exit fullscreen mode

in this way area will automatically change whenever there is any change in dimensions variables and composable observing area will also trigger recomposition.
In this manner it becomes more readable, less error prone

Now you may think this can be achieved by mutableStateOf() with something like



val height by remember{ mutableStateOf(10) }
val width by remember{ mutableStateOf(10) }
val area by remember{ mutableState(height * width) }



Enter fullscreen mode Exit fullscreen mode

Here if there is any change in height and width , you need to manually update it



area = height * width



Enter fullscreen mode Exit fullscreen mode

You can also do this by



val height by remember{ mutableStateOf(10) }
val width by remember{ mutableStateOf(10) }
val area by remember(height,width){ mutableState(height * width) }



Enter fullscreen mode Exit fullscreen mode

now if there is any change in height and weight , area will also update

but here also the main difference is restricting composition count , when you are having long calculations and variable that changes very frequently,

Lets end this with my supporting word for last statement,
where i found this good example at StackOverFlow



@Composable
fun CounterButton() {
    val clicks = remember { mutableStateOf(0) }
    val counter = remember(clicks.value / 5) { mutableStateOf(clicks.value / 5) }

    Button(
        onClick = { clicks.value++ }
    ) {
        Text("${counter.value} clicked")
    }
}



Enter fullscreen mode Exit fullscreen mode

counter variable is supposed to be change on every 5 clicks, say you pressed 30 clicks so then button will recompose on every click but the CounterButton() method will compose 5 times,



@Composable
fun CounterButton() {
    val clicks = remember { mutableStateOf(0) }
    val counter = remember { derivedStateOf { clicks.value / 5 } }

    Button(
        onClick = { clicks.value++ }
    ) {
        Text("${counter.value} clicked")
    }
}


Enter fullscreen mode Exit fullscreen mode

here CounterButton() will have no recomposition,
But there is a huge pitfall or drawback for this, as it will not change the reference of the state object instead rely on state value.
You can learn more here - DerivedState Pitfall

Already the article went long, but if you are here, Thanks a lot for you time and if you want to update any fact , logic to lets bombard comment section and happy coding.

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay