Junior — Middle
At what stage or lifecycle of a React component is the effect launched using LaunchedEffect executed?
sobes.tech AI
Answer from AI
In Jetpack Compose, an effect launched with LaunchedEffect executes within the component's lifecycle. Specifically, LaunchedEffect starts a coroutine when the component first enters the composition with a specified key, and this coroutine is canceled and restarted when the key changes or when the component leaves the composition.
Thus, the effect runs after the component has been composed and displayed, and continues to work as long as the component remains part of the UI. This allows performing asynchronous operations related to the component's lifecycle, such as starting data loads or animations.
Example:
@Composable
fun MyComponent(userId: String) {
LaunchedEffect(userId) {
// This code runs on first display of the component
// and when userId changes
val data = loadData(userId)
// update state with the retrieved data
}
}