How to replace onCommit, onActive, and onDispose in Jetpack Compose
These functions were deprecated in alpha and have been replaced.
If you’re looking at some Jetpack Compose code or tutorials written last year, you might see the use of onCommit
, onActive
, and onDispose
. However, these functions are no longer present in Android’s developer documentation. They were deprecated in version 1.0.0-alpha11 in favor of SideEffect
and DisposableEffect
. Here’s how to use those new functions and update your code.
What do they do?
Composables should be side-effect free and not handle use cases such as connecting with a HTTP API or showing a snackbar directly. You should use the side effect APIs in Jetpack Compose to ensure that these effects are run in a predictable way, rather than writing it alongside your UI rendering code.
onCommit
with just a callback
This simple use case has a simple update. Just use the new SideEffect
function instead.
onCommit
with keys
If you only want to run your side effect when keys are changed, then you should LaunchedEffect
if you don’t call onDispose
. (If you do, scroll down to the next section.)
onCommit
with onDispose
Effects using onDispose
to clean up are now handled in a separate function called DisposableEffect
.
onActive
Rather than having a separate function for running an effect only on the first composition, this use cases is now handled by passing Unit
as a key to LaunchedEffect
or DisposableEffect
. You can pass any static value as a key, including Unit
or true
.