Compose Chronicles: Beyond the UI — The Hidden World of SideEffects 🔍🗝️🔮

Jesseosile
3 min readMay 25, 2024

--

Welcome back, fellow composers! 👋

Remember our adventures with effect handlers? We’ve tackled LaunchedEffect, chilled with DisposableEffect, and even hung out with rememberCoroutineScope.

But what about those times you need a ninja in the background, silently doing its thing without messing up the UI? That’s where our buddy SideEffect comes in! Today, we’re diving into the world of this secret agent of Jetpack Compose and how it keeps things smooth behind the scenes.

So What’s SideEffect About?

It’s basically another Effect Handler in compose used to run operations unrelated to the UI such as logging, updating some state in a ViewModel, or interacting with other parts of the Android system. It ensures that these operations are consistent with the Compose Lifecycle.

Simply think of it as a tool that performs an action based on UI state changes but then doesn’t affect how your UI looks.

Practical Use of SideEffect 💻👨‍💻👩‍💻

SideEffectScreen on device.

We have a screen called SideEffectScreen, this displays 2 buttons spaced evenly at the center of the screen. When either one of the button’s are clicked, the background color of the screen changes.

SideEffectScreen recomposition logged.

When we first launch our app, Logcat shows a recomposition count of 0. This makes sense because it’s the initial composition of the screen — no “re-compositions” have happened yet. However, you might notice a SideEffect being logged even with this initial render. That’s because the SideEffect block runs every time the UI is composed, whether it’s the first time or a subsequent recomposition.

Now, let’s say you click one of the buttons. This action updates the colorType state, triggering a recomposition of the UI. As you've observed in the logs, the SideEffect block gets executed again during this recomposition.

In essence, SideEffect is a powerful tool that runs code in the background whenever the UI composes, regardless of whether it’s the initial rendering or a recomposition due to state changes.

Links to my previous articles in the Compose Chronicles series:

See you on the next one. 😁👋

--

--