Jetpack Compose Side Effects — SideEffect

By Published On: March 20, 2023Categories: Development

Hey folks,
I hope you are doing great. After completing one of my favorite series on SOLID principles let’s talk about another amazing topic that is going to be Jetpack Compose.

So we are going to start with SideEffects of jetpack compose.

What are the side effects in Jetpack Compose? These are not the side effects we usually think of while having medicines :D. They are purely related to Compose adverse effects of re-composing a composable function due to change in the state out of the scope of a composable function.

Key Term: A side-effect is a change to the state of the app that happens outside the scope of a composable function.

Let’s talk about the SideEffect function from side-effects API in compose.

Let’s talk about a use-case before we describe the SideEffect function to understand its use

Consider we are working in a composable function where we need to check/perform something after the successful composition of a given composable function. What will you do to achieve this?

Don’t worry, Compose has solved this problem for you and introduced a Composable SideEffect method for you.

To share Compose state with objects not managed by the Compose, use the SideEffect composable, as it’s invoked on every successful recomposition.

Let’s discuss this with an example so you don’t feel lost by this definition from Android Official Page

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {

    var count by remember { mutableStateOf(0) }

    TestTheme {
        Column {
            // We are updating count state here 
            CustomButton(onClick = { count++ }, count)
        }
    }
}


@Composable
fun CustomButton(onClick: () -> Unit, count: Int) {

    var enableState by remember { mutableStateOf(true) }

    Button(onClick = onClick, enabled = enableState) {
        Text(text = ("Count ").plus(count.toString()))
    }

    SideEffect {
        // We will update button state according to given condition 
        enableState = count < 10
    }
}

in this example, I explained how we disabled a button on a given condition after a successful compose completion.

I hope you understood this example well. For more resources to study please visit this link from the official website.

I’ll come with a new side effect function in the next article till then Bye Bye.

Share this article

Written by : admin

Leave A Comment

Latest Articles