Sobes.tech
Junior — Middle

What is the role of the @Stable annotation in Jetpack Compose and why is it used?

sobes.tech AI

Answer from AI

The @Stable annotation in Jetpack Compose is used to indicate that an object or class is stable from the perspective of the composition system. This means that the state of the object will not change unexpectedly, and its properties will not change without notification.

Role of @Stable:

  • Helps Compose optimize redraws, as the system understands that the object will not change if its reference remains the same.
  • Reduces unnecessary recompositions, improving UI performance.

It is used when you create your own classes or data types that you want to use in Compose and guarantee their stability. If a class is marked @Stable, Compose may not track internal changes and rely on reference integrity.

Example:

@Stable
class User(val name: String, val age: Int)

Here, Compose will consider User objects stable if the reference does not change and will not recompose components unnecessarily.