Junior — Middle
When should you re-initialize the effect launched by LaunchedEffect in Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, the LaunchedEffect should be re-launched when the key parameters it depends on change. This allows reacting to changes in state or input data.
For example, if you use LaunchedEffect to load data based on a user ID, then when this ID changes, the effect should restart to load new data.
@Composable
fun UserProfile(userId: String) {
LaunchedEffect(userId) {
// Load data for the new userId
}
}
If the key (in this case userId) does not change, the effect will not be restarted, preventing unnecessary operations.