<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Esmaeil Beshkar on Medium]]></title>
        <description><![CDATA[Stories by Esmaeil Beshkar on Medium]]></description>
        <link>https://medium.com/@i.beshkar?source=rss-1bfb5869620f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1Pl15-oHI5rwvO0u</url>
            <title>Stories by Esmaeil Beshkar on Medium</title>
            <link>https://medium.com/@i.beshkar?source=rss-1bfb5869620f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:39:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@i.beshkar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Best Practices for Creating UI States in Jetpack Compose]]></title>
            <link>https://medium.com/@i.beshkar/best-practices-for-creating-ui-states-in-jetpack-compose-9bda68cf103c?source=rss-1bfb5869620f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bda68cf103c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-data-class]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <dc:creator><![CDATA[Esmaeil Beshkar]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 09:54:30 GMT</pubDate>
            <atom:updated>2026-06-15T09:54:30.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v15T210oDeoJb3AtXA9oQw.png" /><figcaption>A practical guide to building predictable, scalable UI states in Jetpack Compose.</figcaption></figure><p>Jetpack Compose changes the way we think about Android UI.</p><p>In the View system, it was common to “find a view” and mutate it directly:</p><pre>progressBar.isVisible = true <br>titleTextView.text = user.name <br>errorTextView.isVisible = false</pre><p>In Compose, we do not update views directly. We describe the UI for a given state:</p><pre>when (uiState) { <br>    is ProfileUiState.Loading -&gt; LoadingContent() <br>    is ProfileUiState.Success -&gt; ProfileContent(uiState.user) <br>    is ProfileUiState.Error -&gt; ErrorContent(uiState.message) <br>}</pre><p>That sounds simple, but in real projects UI state can quickly become messy:</p><pre>data class UiState( <br>    val isLoading: Boolean = false, <br>    val user: User? = null, <br>    val error: String? = null, <br>    val isRefreshing: Boolean = false, <br>    val shouldNavigateBack: Boolean = false, <br>    val snackbarMessage: String? = null <br>)</pre><p>At first, this looks fine. After a few features, it becomes hard to understand:</p><p>Can isLoading = true and user != null happen together?<br>Can error != null and user != null happen together?<br>Who clears snackbarMessage?<br>What happens after rotation?<br>Is shouldNavigateBack really state, or is it an event?</p><p>This article is a practical deep dive into creating clean, scalable, and maintainable UI states in Jetpack Compose.</p><h3>1. Start with the most important rule: UI is a function of state</h3><p>A composable should not decide “what happened in the past”. It should render “what is true now”.</p><p>A good mental model is:</p><pre>UI = f(state)</pre><p>So instead of thinking:</p><blockquote>When API call starts, show progress. When API call succeeds, hide progress and show data. When it fails, show error.</blockquote><p>Think:</p><blockquote>If state is Loading, render loading.<br>If state is Success, render content.<br>If state is Error, render error.</blockquote><p>That small shift makes your UI easier to reason about, test, preview, and maintain.</p><h3>2. Separate screen UI state from UI element state</h3><p>Not every state belongs in the same place.</p><p>In Compose, I usually think about two types of state:</p><h3>Screen UI state</h3><p>This is the state needed to render the whole screen.</p><p>Examples:</p><pre>val user: UserUiModel <br>val posts: List&lt;PostUiModel&gt; <br>val isLoading: Boolean <br>val errorMessage: String? <br>val selectedFilter: Filter</pre><p>This state usually comes from a ViewModel, because it depends on repositories, use cases, network responses, database data, or business rules.</p><h3>UI element state</h3><p>This is small state that belongs to one UI component.</p><p>Examples:</p><pre>val isDropdownExpanded: Boolean <br>val isPasswordVisible: Boolean <br>val selectedTabIndex: Int <br>val lazyListState: LazyListState <br>val snackbarHostState: SnackbarHostState</pre><p>This state is often better kept inside the composable using remember or rememberSaveable, unless another composable also needs to control it.</p><p>Example:</p><pre>@Composable<br>fun PasswordTextField(<br>    value: String,<br>    onValueChange: (String) -&gt; Unit<br>) {<br>    var passwordVisible by rememberSaveable { mutableStateOf(false) }<br><br>    OutlinedTextField(<br>        value = value,<br>        onValueChange = onValueChange,<br>        visualTransformation = if (passwordVisible) {<br>            VisualTransformation.None<br>        } else {<br>            PasswordVisualTransformation()<br>        },<br>        trailingIcon = {<br>            IconButton(onClick = { passwordVisible = !passwordVisible }) {<br>                Icon(<br>                    imageVector = if (passwordVisible) {<br>                        Icons.Default.VisibilityOff<br>                    } else {<br>                        Icons.Default.Visibility<br>                    }, contentDescription = null<br>                )<br>            }<br>        }<br>    )<br>}</pre><p>passwordVisible does not need to be in the ViewModel unless there is a real business reason for it.</p><h3>3. Hoist state only as high as necessary</h3><p>State hoisting means moving state to the caller.</p><p>A stateful composable owns its own state:</p><pre>@Composable<br>fun SearchBox() {<br>    var query by rememberSaveable { mutableStateOf(&quot;&quot;) }<br><br>    OutlinedTextField(<br>        value = query,<br>        onValueChange = { query = it }<br>    )<br>}</pre><p>A stateless composable receives state and exposes events:</p><pre>@Composable<br>fun SearchBox(<br>    query: String,<br>    onQueryChange: (String) -&gt; Unit<br>) {<br>    OutlinedTextField(<br>        value = query, <br>        onValueChange = onQueryChange<br>    )<br>}</pre><p>The stateless version is more reusable, testable, and preview-friendly.</p><p>A good rule:</p><blockquote>Keep state as close as possible to where it is used, but high enough that all readers and writers can access it.</blockquote><p>Do not move everything to the ViewModel by default.</p><p>For example, this is usually unnecessary:</p><pre>class LoginViewModel : ViewModel() {<br>    var isPasswordVisible by mutableStateOf(false) <br>        private set<br>    <br>    fun togglePasswordVisibility() {<br>        isPasswordVisible = !isPasswordVisible<br>    }<br>}</pre><p>This is often enough:</p><pre>var isPasswordVisible by rememberSaveable { mutableStateOf(false) }</pre><p>But this should be in the ViewModel:</p><pre>class LoginViewModel(<br>    private val loginUseCase: LoginUseCase<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow(LoginUiState())<br>    val uiState = _uiState.asStateFlow()<br><br>    fun login() {<br>        // Business logic belongs here <br>    }<br>}</pre><p>The difference is simple:</p><p>If it is only about how a component looks, keep it in the UI.<br>If it is about business logic, data loading, validation, permissions, authentication, or persistence, use a state holder such as a ViewModel.</p><h3>4. Prefer immutable UI state</h3><p>Your UI state should describe the screen at a moment in time. It should not be mutated from random places.</p><p>Prefer this:</p><pre>data class LoginUiState(<br>    val email: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val isLoading: Boolean = false,<br>    val emailError: String? = null,<br>    val passwordError: String? = null,<br>    val userMessage: String? = null<br>)</pre><p>Expose it like this:</p><pre>class LoginViewModel(<br>    private val loginUseCase: LoginUseCase<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow(LoginUiState())<br>    val uiState: StateFlow&lt;LoginUiState&gt; = _uiState.asStateFlow()<br><br>    fun onEmailChange(email: String) {<br>        _uiState.update {<br>            it.copy(<br>                email = email,<br>                emailError = null<br>            )<br>        }<br>    }<br><br>    fun onPasswordChange(password: String) {<br>        _uiState.update {<br>            it.copy(<br>                password = password,<br>                passwordError = null<br>            )<br>        }<br>    }<br>}</pre><p>Avoid exposing mutable state directly:</p><pre>// Avoid this<br>val uiState = MutableStateFlow(LoginUiState())</pre><p>The UI should observe state and send events. It should not directly modify the state holder.</p><h3>5. Use Unidirectional Data Flow</h3><p>A clean Compose screen usually follows this direction:</p><pre>State flows down<br>Events flow up</pre><p>The ViewModel exposes state:</p><pre>val uiState: StateFlow&lt;LoginUiState&gt;</pre><p>The composable collects it:</p><pre>@Composable<br>fun LoginRoute(<br>    viewModel: LoginViewModel = hiltViewModel(),<br>    onLoginSuccess: () -&gt; Unit<br>) {<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br><br>    LoginScreen(<br>        uiState = uiState,<br>        onEmailChange = viewModel::onEmailChange,<br>        onPasswordChange = viewModel::onPasswordChange,<br>        onLoginClick = viewModel::login<br>    )<br>}</pre><p>The screen renders state and sends user actions back:</p><pre>@Composable<br>fun LoginScreen(<br>    uiState: LoginUiState,<br>    onEmailChange: (String) -&gt; Unit,<br>    onPasswordChange: (String) -&gt; Unit,<br>    onLoginClick: () -&gt; Unit<br>) {<br>    Column {<br>        OutlinedTextField(<br>            value = uiState.email,<br>            onValueChange = onEmailChange,<br>            isError = uiState.emailError != null,<br>            label = { Text(&quot;Email&quot;) },<br>            supportingText = {<br>                uiState.emailError?.let { Text(it) }<br>            }<br>        )<br><br>        OutlinedTextField(<br>            value = uiState.password,<br>            onValueChange = onPasswordChange,<br>            isError = uiState.passwordError != null,<br>            label = { Text(&quot;Password&quot;) },<br>            supportingText = { uiState.passwordError?.let { Text(it) } }<br>        )<br><br>        Button(<br>            onClick = onLoginClick, <br>            enabled = !uiState.isLoading<br>        ) {<br>            if (uiState.isLoading) {<br>                CircularProgressIndicator()<br>            } else {<br>                Text(&quot;Login&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>This makes the screen predictable.</p><p>The UI does not know how login works.<br>The ViewModel does not know how the button looks.<br>Each part has a clear responsibility.</p><h3>6. Do not pass ViewModel deep into composables</h3><p>This is a common mistake:</p><pre>@Composable<br>fun LoginScreen(viewModel: LoginViewModel) {<br>    LoginForm(viewModel)<br>}<br><br>@Composable<br>fun LoginForm(viewModel: LoginViewModel) {<br>    EmailField(viewModel)<br>}<br><br>@Composable<br>fun EmailField(viewModel: LoginViewModel) {<br>    OutlinedTextField(<br>        value = viewModel.uiState.value.email,<br>        onValueChange = viewModel::onEmailChange<br>    )<br>}</pre><p>This couples every small component to a specific ViewModel.</p><p>Instead, inject the ViewModel at the route/screen entry point and pass only what each composable needs:</p><pre>@Composable<br>fun LoginRoute(<br>    viewModel: LoginViewModel = hiltViewModel()<br>) {<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br><br>    LoginScreen(<br>        uiState = uiState,<br>        onEmailChange = viewModel::onEmailChange,<br>        onPasswordChange = viewModel::onPasswordChange,<br>        onLoginClick = viewModel::login<br>    )<br>}</pre><p>Then your UI components stay reusable:</p><pre>@Composable<br>fun EmailField(<br>    email: String,<br>    error: String?,<br>    onEmailChange: (String) -&gt; Unit<br>) {<br>    OutlinedTextField(<br>        value = email,<br>        onValueChange = onEmailChange,<br>        isError = error != null,<br>        label = { Text(&quot;Email&quot;) },<br>        supportingText = {<br>            error?.let { Text(it) }<br>        }<br>    )<br>}</pre><p>Now EmailField can be used in login, signup, profile editing, preview screens, and tests.</p><h3>7. Choose the right shape for your UI state</h3><p>There is no single perfect UI state model. The best shape depends on the screen.</p><p>But there are some common patterns.</p><h4>Pattern 1: Simple data class</h4><p>Use a data class when the screen can show multiple independent pieces of state at the same time.</p><p>Example: login screen.</p><pre>data class LoginUiState(<br>    val email: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val isLoading: Boolean = false,<br>    val emailError: String? = null,<br>    val passwordError: String? = null,<br>    val userMessage: String? = null<br>)</pre><p>This is practical because the screen can have:</p><ul><li>email text</li><li>password text</li><li>field errors</li><li>loading state</li><li>snackbar message</li></ul><p>all at the same time.</p><h4>Pattern 2: Sealed interface for mutually exclusive states</h4><p>Use a sealed interface when the screen has clear, exclusive states.</p><p>Example: profile screen.</p><pre>sealed interface ProfileUiState {<br>    data object Loading : ProfileUiState<br><br>    data class Success(<br>        val user: UserUiModel<br>    ) : ProfileUiState<br><br>    data class Error(<br>        val message: String<br>    ) : ProfileUiState<br>}</pre><p>Then rendering becomes very clear:</p><pre>@Composable<br>fun ProfileScreen(<br>    uiState: ProfileUiState,<br>    onRetryClick: () -&gt; Unit<br>) {<br>    when (uiState) {<br>        ProfileUiState.Loading -&gt; {<br>            LoadingContent()<br>        }<br><br>        is ProfileUiState.Success -&gt; {<br>            ProfileContent(user = uiState.user)<br>        }<br><br>        is ProfileUiState.Error -&gt; {<br>            ErrorContent(message = uiState.message, onRetryClick = onRetryClick)<br>        }<br>    }<br>}</pre><p>This avoids impossible combinations like:</p><pre>isLoading = true<br>user = someUser<br>error = &quot;Something went wrong&quot;</pre><p>If those states should not happen together, model them as separate types.</p><h4>Pattern 3: Content state with partial loading</h4><p>Sometimes a screen already has content, but also needs to refresh.</p><p>For example, a feed screen can show old posts while refreshing new posts.</p><p>In that case, this sealed state may be too limited:</p><pre>sealed interface FeedUiState {<br>    data object Loading : FeedUiState<br>    data class Success(val posts: List&lt;PostUiModel&gt;) : FeedUiState<br>    data class Error(val message: String) : FeedUiState<br>}</pre><p>Because the screen may need content and loading at the same time.</p><p>A better model:</p><pre>data class FeedUiState(<br>    val posts: List&lt;PostUiModel&gt; = emptyList(),<br>    val isInitialLoading: Boolean = true,<br>    val isRefreshing: Boolean = false,<br>    val errorMessage: String? = null<br>)</pre><p>Now the UI can show:</p><ul><li>full-screen loading for first load</li><li>pull-to-refresh loading when content already exists</li><li>snackbar error while keeping old content visible</li></ul><p>Example:</p><pre>@Composable<br>fun FeedScreen(<br>    uiState: FeedUiState,<br>    onRefresh: () -&gt; Unit<br>) {<br>    when {<br>        uiState.isInitialLoading -&gt; {<br>            LoadingContent()<br>        }<br><br>        uiState.posts.isEmpty() -&gt; {<br>            EmptyContent()<br>        }<br><br>        else -&gt; {<br>            FeedContent(<br>                posts = uiState.posts,<br>                isRefreshing = uiState.isRefreshing,<br>                onRefresh = onRefresh<br>            )<br>        }<br>    }<br>}</pre><p>The point is not “always use sealed classes” or “always use data classes”.</p><p>The point is:</p><blockquote>Your UI state should make invalid states difficult or impossible to represent.</blockquote><h3>8. Avoid nullable soup</h3><p>This is a smell:</p><pre>data class ProductUiState(<br>    val product: ProductUiModel? = null,<br>    val error: String? = null,<br>    val isLoading: Boolean = false<br>)</pre><p>It allows unclear combinations:</p><pre>product = null<br>error = null<br>isLoading = false</pre><p>What should the UI show here?</p><p>A blank screen?<br>An empty state?<br>A bug?</p><p>A sealed model is clearer:</p><pre>sealed interface ProductUiState {<br>    data object Loading : ProductUiState<br>    data class Success(val product: ProductUiModel) : ProductUiState<br>    data class Error(val message: String) : ProductUiState<br>}</pre><p>Now every possible state has meaning.</p><h3>9. Keep domain models away from the UI</h3><p>It is tempting to expose domain or database models directly:</p><pre>data class User(<br>    val id: String,<br>    val firstName: String,<br>    val lastName: String,<br>    val birthday: LocalDate?,<br>    val avatarUrl: String?<br>)</pre><p>and then use it directly in Compose:</p><pre>Text(&quot;${user.firstName} ${user.lastName}&quot;)</pre><p>This works, but it spreads formatting logic into the UI.</p><p>Prefer a UI model:</p><pre>data class UserUiModel(<br>    val id: String,<br>    val fullName: String,<br>    val avatarUrl: String?,<br>    val birthdayLabel: String<br>)</pre><p>Map it before exposing it to the UI:</p><pre>fun User.toUiModel(): UserUiModel {<br>    return UserUiModel(<br>        id = id,<br>        fullName = &quot;$firstName $lastName&quot;,<br>        avatarUrl = avatarUrl,<br>        birthdayLabel = birthday?.toString() ?: &quot;Not provided&quot;<br>    )<br>}</pre><p>Now the composable is simple:</p><pre>@Composable<br>fun UserHeader(user: UserUiModel) {<br>    Column {<br>        Text(text = user.fullName)<br>        Text(text = user.birthdayLabel)<br>    }<br>}</pre><p>The UI should not need to understand domain rules. It should display already prepared data.</p><h3>10. Use StateFlow for screen UI state</h3><p>For most screen-level UI state, StateFlow works very well.</p><p>Example:</p><pre>class ProfileViewModel(<br>    private val getProfileUseCase: GetProfileUseCase<br>) : ViewModel() {<br><br>    val uiState: StateFlow&lt;ProfileUiState&gt; =<br>        getProfileUseCase().map { profile -&gt;<br>            ProfileUiState.Success(<br>                user = profile.toUiModel()<br>            )<br>        }<br>            .catch { throwable -&gt;<br>                emit(<br>                    ProfileUiState.Error(<br>                        message = throwable.message ?: &quot;Something went wrong&quot;<br>                    )<br>                )<br>            }<br>            .stateIn(<br>                scope = viewModelScope,<br>                started = SharingStarted.WhileSubscribed(5_000),<br>                initialValue = ProfileUiState.Loading<br>            )<br>}</pre><p>Then collect it in Compose:</p><pre>@Composable<br>fun ProfileRoute(<br>    viewModel: ProfileViewModel = hiltViewModel()<br>) {<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br>    <br>    ProfileScreen(<br>        uiState = uiState,<br>        onRetryClick = viewModel::retry<br>    )<br>}</pre><p>Use collectAsStateWithLifecycle() instead of manually collecting flows in LaunchedEffect for normal UI state.</p><h3>11. Be careful with one-time events</h3><p>A common question is:</p><blockquote>Should navigation, Toasts, and Snackbars be part of UI state?</blockquote><p>The answer is: be intentional.</p><p>State is something that exists.<br>Events are something that happen.</p><p>A loading state exists.<br>A list of messages exists.<br>An error message displayed on screen exists.</p><p>But “navigate now” is not really screen state. It is an effect.</p><p>For example, after login succeeds, you might be tempted to do this:</p><pre>data class LoginUiState(<br>    val shouldNavigateToHome: Boolean = false<br>)</pre><p>Then in Compose:</p><pre>if (uiState.shouldNavigateToHome) {<br>    navController.navigate(&quot;home&quot;)<br>}</pre><p>This is dangerous because composables can recompose many times. You should not perform navigation directly during composition.</p><p>Use LaunchedEffect:</p><pre>LaunchedEffect(uiState.isLoginSuccessful) {<br>    if (uiState.isLoginSuccessful) {<br>        onLoginSuccess()<br>        viewModel.onLoginNavigationHandled()<br>    }<br>}</pre><p>And in the ViewModel:</p><pre>fun onLoginNavigationHandled() {<br>    _uiState.update {<br>        it.copy(isLoginSuccessful = false)<br>    }<br>}</pre><p>For snackbars, a practical approach is to model the message as state and clear it after it is shown:</p><pre>data class LoginUiState(<br>    val email: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val isLoading: Boolean = false,<br>    val userMessage: String? = null<br>)</pre><p>In Compose:</p><pre>@Composable<br>fun LoginRoute(<br>    viewModel: LoginViewModel = hiltViewModel()<br>) {<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br>    val snackbarHostState = remember { SnackbarHostState() }<br><br>    LaunchedEffect(uiState.userMessage) {<br>        val message = uiState.userMessage ?: return@LaunchedEffect<br>        snackbarHostState.showSnackbar(message)<br>        viewModel.onUserMessageShown()<br>    }<br><br>    Scaffold(<br>        snackbarHost = {<br>            SnackbarHost(hostState = snackbarHostState)<br>        }<br>    ) { paddingValues -&gt;<br>        LoginScreen(<br>            modifier = Modifier.padding(paddingValues),<br>            uiState = uiState,<br>            onEmailChange = viewModel::onEmailChange,<br>            onPasswordChange = viewModel::onPasswordChange,<br>            onLoginClick = viewModel::login<br>        )<br>    }<br>}</pre><p>In the ViewModel:</p><pre>fun onUserMessageShown() {<br>    _uiState.update {<br>        it.copy(userMessage = null)<br>    }<br>}</pre><p>This keeps side effects controlled and avoids running them directly inside composition.</p><h3>12. Do validation in the right place</h3><p>Input validation is a good example of state ownership.</p><p>Simple visual-only validation can stay close to the UI. But validation that affects business rules should usually be handled by the ViewModel or domain layer.</p><p>Example:</p><pre>fun login() {<br>    val currentState = _uiState.value<br><br>    val emailError = validateEmail(currentState.email)<br>    val passwordError = validatePassword(currentState.password)<br><br>    if (emailError != null || passwordError != null) {<br>        _uiState.update {<br>            it.copy(<br>                emailError = emailError,<br>                passwordError = passwordError<br>            )<br>        }<br>        return<br>    }<br><br>    submitLogin()<br>}</pre><p>The UI simply displays the result:</p><pre>OutlinedTextField(<br>    value = uiState.email,<br>    onValueChange = onEmailChange,<br>    isError = uiState.emailError != null,<br>    supportingText = {<br>        uiState.emailError?.let { Text(it) }<br>    }<br>)</pre><p>This keeps validation consistent across recompositions, configuration changes, and tests.</p><h3>13. Keep loading states specific</h3><p>Avoid using one generic isLoading for everything.</p><p>For example:</p><pre>data class ProfileUiState(<br>    val isLoading: Boolean = false,<br>    val isUpdatingAvatar: Boolean = false,<br>    val isRefreshing: Boolean = false<br>)</pre><p>This is better than:</p><pre>data class ProfileUiState(<br>    val isLoading: Boolean = false<br>)</pre><p>Because different loading states can affect different UI parts.</p><p>Initial screen loading may show a full-screen progress indicator.<br>Refreshing may show pull-to-refresh.<br>Updating avatar may show loading only on the avatar section.<br>Submitting a form may disable only the submit button.</p><p>Your state should be specific enough to support good UX.</p><h3>14. Model empty state explicitly</h3><p>Empty is not always error.</p><p>A screen can have:</p><ul><li>loading state</li><li>content state</li><li>empty state</li><li>error state</li></ul><p>Example:</p><pre>sealed interface OrdersUiState {<br>    data object Loading : OrdersUiState<br><br>    data object Empty : OrdersUiState<br><br>    data class Success(<br>        val orders: List&lt;OrderUiModel&gt;<br>    ) : OrdersUiState<br><br>    data class Error(<br>        val message: String<br>    ) : OrdersUiState<br>}</pre><p>This makes the UI clear:</p><pre>when (uiState) {<br>    OrdersUiState.Loading -&gt; LoadingContent()<br>    OrdersUiState.Empty -&gt; EmptyOrdersContent()<br>    is OrdersUiState.Success -&gt; OrdersList(uiState.orders)<br>    is OrdersUiState.Error -&gt; ErrorContent(uiState.message)<br>}</pre><p>Do not force empty lists and errors into the same state.</p><h3>15. Use stable and immutable state when possible</h3><p>Compose works best when it can understand whether data has changed.</p><p>Prefer immutable state:</p><pre>data class ChatUiState(<br>    val messages: List&lt;MessageUiModel&gt; = emptyList(),<br>    val input: String = &quot;&quot;,<br>    val isSending: Boolean = false<br>)</pre><p>Avoid mutable lists in UI state:</p><pre>// Avoid<br>data class ChatUiState(<br>    val messages: MutableList&lt;MessageUiModel&gt; = mutableListOf()<br>)</pre><p>If you mutate a list in place, Compose may not observe the change correctly or your UI may become harder to reason about.</p><p>Prefer creating a new list:</p><pre>_uiState.update { state -&gt;<br>    state.copy(<br>        messages = state.messages + newMessage<br>    )<br>}</pre><p>For performance-sensitive screens, especially large lists, also pay attention to Compose stability. Immutable data models and stable parameters help Compose skip unnecessary work.</p><h3>16. Avoid doing heavy work inside composables</h3><p>Composable functions can run many times. Do not put expensive calculations directly in the composable body.</p><p>Avoid:</p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;) {<br>    val sortedUsers = users.sortedBy { it.name }<br><br>    LazyColumn {<br>        items(sortedUsers) { user -&gt;<br>            Text(user.name)<br>        }<br>    }<br>}</pre><p>Better:</p><pre>@Composable<br>fun UserList(users: List&lt;User&gt;) {<br>    val sortedUsers = remember(users) {<br>        users.sortedBy { it.name }<br>    }<br><br>    LazyColumn {<br>        items(<br>            items = sortedUsers,<br>            key = { it.id }<br>        ) { user -&gt;<br>            Text(user.name)<br>        }<br>    }<br>}</pre><p>Even better, if sorting is business logic or part of state preparation, do it before the UI:</p><pre>data class UsersUiState(<br>    val users: List&lt;UserUiModel&gt; = emptyList()<br>)</pre><p>Then the composable only renders.</p><h3>17. Use keys in lazy lists</h3><p>When rendering lists, provide stable keys:</p><pre>LazyColumn {<br>    items(<br>        items = uiState.messages,<br>        key = { message -&gt; message.id }<br>    ) { message -&gt;<br>        MessageItem(message = message)<br>    }<br>}</pre><p>This helps Compose keep item identity when the list changes.</p><p>It is especially important when list items have remembered state, animations, or reorder behavior.</p><h3>18. Save only what needs to survive</h3><p>remember survives recomposition.</p><pre>var expanded by remember { mutableStateOf(false) }</pre><p>rememberSaveable survives configuration changes and process recreation when the value can be saved in a Bundle.</p><pre>var query by rememberSaveable { mutableStateOf(&quot;&quot;) }</pre><p>ViewModel survives configuration changes, but not system-initiated process death.</p><p>For process death, use SavedStateHandle carefully.</p><p>The important rule:</p><blockquote>Save the minimum needed to restore the screen.</blockquote><p>Do not store large objects in saved state.</p><p>Instead of saving a whole user profile:</p><pre>// Avoid saving large objects<br>savedStateHandle[&quot;user&quot;] = user</pre><p>Save the ID:</p><pre>savedStateHandle[&quot;userId&quot;] = userId</pre><p>Then reload the details from the repository.</p><h3>19. A complete example: Login screen state</h3><p>Let’s put everything together.</p><h3>UI state</h3><pre>data class LoginUiState(<br>    val email: String = &quot;&quot;,<br>    val password: String = &quot;&quot;,<br>    val isLoading: Boolean = false,<br>    val emailError: String? = null,<br>    val passwordError: String? = null,<br>    val userMessage: String? = null,<br>    val isLoginSuccessful: Boolean = false<br>)</pre><h4>ViewModel</h4><pre>class LoginViewModel(<br>    private val loginUseCase: LoginUseCase<br>) : ViewModel() {<br><br>    private val _uiState = MutableStateFlow(LoginUiState())<br>    val uiState: StateFlow&lt;LoginUiState&gt; = _uiState.asStateFlow()<br><br>    fun onEmailChange(email: String) {<br>        _uiState.update {<br>            it.copy(<br>                email = email,<br>                emailError = null<br>            )<br>        }<br>    }<br><br>    fun onPasswordChange(password: String) {<br>        _uiState.update {<br>            it.copy(<br>                password = password,<br>                passwordError = null<br>            )<br>        }<br>    }<br><br>    fun login() {<br>        val state = _uiState.value<br><br>        val emailError = validateEmail(state.email)<br>        val passwordError = validatePassword(state.password)<br><br>        if (emailError != null || passwordError != null) {<br>            _uiState.update {<br>                it.copy(<br>                    emailError = emailError,<br>                    passwordError = passwordError<br>                )<br>            }<br>            return<br>        }<br><br>        viewModelScope.launch {<br>            _uiState.update {<br>                it.copy(isLoading = true)<br>            }<br><br>            val result = loginUseCase(<br>                email = state.email,<br>                password = state.password<br>            )<br><br>            result<br>                .onSuccess {<br>                    _uiState.update {<br>                        it.copy(<br>                            isLoading = false,<br>                            isLoginSuccessful = true<br>                        )<br>                    }<br>                }<br>                .onFailure { throwable -&gt;<br>                    _uiState.update {<br>                        it.copy(<br>                            isLoading = false,<br>                            userMessage = throwable.message ?: &quot;Login failed&quot;<br>                        )<br>                    }<br>                }<br>        }<br>    }<br><br>    fun onUserMessageShown() {<br>        _uiState.update {<br>            it.copy(userMessage = null)<br>        }<br>    }<br><br>    fun onLoginNavigationHandled() {<br>        _uiState.update {<br>            it.copy(isLoginSuccessful = false)<br>        }<br>    }<br><br>    private fun validateEmail(email: String): String? {<br>        return when {<br>            email.isBlank() -&gt; &quot;Email is required&quot;<br>            !email.contains(&quot;@&quot;) -&gt; &quot;Invalid email address&quot;<br>            else -&gt; null<br>        }<br>    }<br><br>    private fun validatePassword(password: String): String? {<br>        return when {<br>            password.isBlank() -&gt; &quot;Password is required&quot;<br>            password.length &lt; 8 -&gt; &quot;Password must be at least 8 characters&quot;<br>            else -&gt; null<br>        }<br>    }<br>}</pre><h4>Route composable</h4><pre>@Composable<br>fun LoginRoute(<br>    viewModel: LoginViewModel = hiltViewModel(),<br>    onLoginSuccess: () -&gt; Unit<br>) {<br>    val uiState by viewModel.uiState.collectAsStateWithLifecycle()<br>    val snackbarHostState = remember { SnackbarHostState() }<br><br>    LaunchedEffect(uiState.userMessage) {<br>        val message = uiState.userMessage ?: return@LaunchedEffect<br>        snackbarHostState.showSnackbar(message)<br>        viewModel.onUserMessageShown()<br>    }<br><br>    LaunchedEffect(uiState.isLoginSuccessful) {<br>        if (uiState.isLoginSuccessful) {<br>            onLoginSuccess()<br>            viewModel.onLoginNavigationHandled()<br>        }<br>    }<br><br>    Scaffold(<br>        snackbarHost = {<br>            SnackbarHost(hostState = snackbarHostState)<br>        }<br>    ) { paddingValues -&gt;<br>        LoginScreen(<br>            modifier = Modifier.padding(paddingValues),<br>            uiState = uiState,<br>            onEmailChange = viewModel::onEmailChange,<br>            onPasswordChange = viewModel::onPasswordChange,<br>            onLoginClick = viewModel::login<br>        )<br>    }<br>}</pre><h4>Screen composable</h4><pre>@Composable<br>fun LoginScreen(<br>    uiState: LoginUiState,<br>    onEmailChange: (String) -&gt; Unit,<br>    onPasswordChange: (String) -&gt; Unit,<br>    onLoginClick: () -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br>    Column(<br>        modifier = modifier<br>            .fillMaxSize()<br>            .padding(24.dp),<br>        verticalArrangement = Arrangement.Center<br>    ) {<br>        OutlinedTextField(<br>            modifier = Modifier.fillMaxWidth(),<br>            value = uiState.email,<br>            onValueChange = onEmailChange,<br>            label = { Text(&quot;Email&quot;) },<br>            isError = uiState.emailError != null,<br>            supportingText = {<br>                uiState.emailError?.let { Text(it) }<br>            },<br>            enabled = !uiState.isLoading<br>        )<br><br>        Spacer(modifier = Modifier.height(12.dp))<br><br>        OutlinedTextField(<br>            modifier = Modifier.fillMaxWidth(),<br>            value = uiState.password,<br>            onValueChange = onPasswordChange,<br>            label = { Text(&quot;Password&quot;) },<br>            isError = uiState.passwordError != null,<br>            supportingText = {<br>                uiState.passwordError?.let { Text(it) }<br>            },<br>            visualTransformation = PasswordVisualTransformation(),<br>            enabled = !uiState.isLoading<br>        )<br><br>        Spacer(modifier = Modifier.height(24.dp))<br><br>        Button(<br>            modifier = Modifier.fillMaxWidth(),<br>            onClick = onLoginClick,<br>            enabled = !uiState.isLoading<br>        ) {<br>            if (uiState.isLoading) {<br>                CircularProgressIndicator(<br>                    modifier = Modifier.size(20.dp),<br>                    strokeWidth = 2.dp<br>                )<br>            } else {<br>                Text(&quot;Login&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>This structure gives us:</p><ul><li>one source of truth</li><li>lifecycle-aware state collection</li><li>controlled side effects</li><li>testable business logic</li><li>reusable UI components</li><li>preview-friendly composables</li></ul><h3>20. Preview becomes easier with good UI state</h3><p>When your composables receive plain state, previews become very easy.</p><pre>@Preview(showBackground = true)<br>@Composable<br>private fun LoginScreenPreview() {<br>    LoginScreen(<br>        uiState = LoginUiState(<br>            email = &quot;esmaeil@example.com&quot;,<br>            password = &quot;password123&quot;<br>        ),<br>        onEmailChange = {},<br>        onPasswordChange = {},<br>        onLoginClick = {}<br>    )<br>}</pre><p>Error preview:</p><pre>@Preview(showBackground = true)<br>@Composable<br>private fun LoginScreenErrorPreview() {<br>    LoginScreen(<br>        uiState = LoginUiState(<br>            email = &quot;wrong-email&quot;,<br>            password = &quot;123&quot;,<br>            emailError = &quot;Invalid email address&quot;,<br>            passwordError = &quot;Password must be at least 8 characters&quot;<br>        ),<br>        onEmailChange = {},<br>        onPasswordChange = {},<br>        onLoginClick = {}<br>    )<br>}</pre><p>Loading preview:</p><pre>@Preview(showBackground = true)<br>@Composable<br>private fun LoginScreenLoadingPreview() {<br>    LoginScreen(<br>        uiState = LoginUiState(<br>            email = &quot;esmaeil@example.com&quot;,<br>            password = &quot;password123&quot;,<br>            isLoading = true<br>        ),<br>        onEmailChange = {},<br>        onPasswordChange = {},<br>        onLoginClick = {}<br>    )<br>}</pre><p>This is one of the biggest benefits of clean UI state: you can preview real screen situations without running the whole app.</p><h3>21. Testing also becomes easier</h3><p>When your ViewModel exposes a clear state, testing is straightforward.</p><p>Example:</p><pre>@Test<br>fun login_withInvalidEmail_updatesEmailError() = runTest {<br>    val viewModel = LoginViewModel(<br>        loginUseCase = fakeLoginUseCase<br>    )<br><br>    viewModel.onEmailChange(&quot;wrong-email&quot;)<br>    viewModel.onPasswordChange(&quot;password123&quot;)<br>    viewModel.login()<br><br>    val state = viewModel.uiState.value<br><br>    assertEquals(&quot;Invalid email address&quot;, state.emailError)<br>}</pre><p>You are not testing Compose.<br>You are testing state production.</p><p>That is exactly what the ViewModel should be responsible for.</p><h3>22. Common mistakes to avoid</h3><h4>Mistake 1: Too many nullable fields</h4><pre>data class UiState(<br>    val data: Data? = null,<br>    val error: String? = null<br>)</pre><p>Ask yourself:</p><p>What does it mean when both are null?<br>What does it mean when both are not null?</p><p>If the answer is unclear, use a sealed type.</p><h4>Mistake 2: Passing ViewModel everywhere</h4><p>Avoid making every composable depend on your ViewModel.</p><p>Pass state and callbacks instead.</p><h4>Mistake 3: Doing navigation directly in composition</h4><p>Avoid:</p><pre>if (uiState.isSuccess) {<br>    navController.navigate(&quot;home&quot;)<br>}</pre><p>Use LaunchedEffect.</p><h4>Mistake 4: Putting all UI element state in ViewModel</h4><p>Not everything belongs in the ViewModel.</p><p>Dropdown expanded state, password visibility, local tab selection, and scroll state are often UI concerns.</p><h4>Mistake 5: Mutating lists in place</h4><p>Avoid:</p><pre>state.messages.add(newMessage)</pre><p>Prefer:</p><pre>state.copy(messages = state.messages + newMessage)</pre><p>Immutable updates are easier to reason about and safer with Compose.</p><h4>Mistake 6: One generic loading flag for everything</h4><p>Instead of:</p><pre>val isLoading: Boolean</pre><p>consider:</p><pre>val isInitialLoading: Boolean<br>val isRefreshing: Boolean<br>val isSubmitting: Boolean</pre><p>Specific state creates better UX.</p><h3>Final checklist</h3><p>When creating UI state in Compose, ask yourself:</p><ol><li>Does this state describe the screen right now?</li><li>Is this state UI logic or business logic?</li><li>Who needs to read this state?</li><li>Who needs to change this state?</li><li>Is the state hoisted only as high as necessary?</li><li>Can impossible states be represented?</li><li>Is the UI state immutable from the UI?</li><li>Is the composable receiving state and exposing events?</li><li>Are one-time effects handled safely?</li><li>Can I preview this screen easily?</li></ol><p>If the answer to these questions is clear, your Compose UI state is probably in a good shape.</p><h3>Conclusion</h3><p>Good UI state design is one of the most important skills in Jetpack Compose.</p><p>It affects everything:</p><ul><li>readability</li><li>testability</li><li>previews</li><li>performance</li><li>navigation</li><li>error handling</li><li>long-term maintainability</li></ul><p>The goal is not to create a complicated architecture. The goal is to make the screen easy to understand.</p><p>A good Compose screen should feel boring in the best way:</p><p>State comes in.<br>Events go out.<br>The UI renders.</p><p>That is the foundation of clean Compose development.</p><blockquote>Compose rewards clarity. The better we model our UI state, the simpler our UI becomes.</blockquote><p><em>Happy composing — and may your UI states always be predictable, previewable, and free from nullable chaos.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bda68cf103c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Repeating Compose Preview Boilerplate]]></title>
            <link>https://medium.com/@i.beshkar/stop-repeating-compose-preview-boilerplate-9cf18732c270?source=rss-1bfb5869620f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cf18732c270</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[preview]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Esmaeil Beshkar]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 09:10:07 GMT</pubDate>
            <atom:updated>2026-06-11T09:10:07.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xb7LO_f2VehG1v3Rc-KUQ.png" /><figcaption><em>One small annotation can turn a pile of one-off Compose previews into a reusable workflow.</em></figcaption></figure><p>In Jetpack Compose, preview tooling is already good enough to keep you out of the emulator for a lot of day-to-day UI iteration. Android Studio can render composables directly in the design surface, supports multiple preview variants, and even lets you bundle several @Preview configurations into a single custom multipreview annotation.</p><p>That is exactly the problem I wanted to solve in my own project.</p><p>I was tired of writing a separate preview for every recurring UI check: small phone, normal phone, large phone, dark mode, large font, tablet portrait, tablet landscape. The screen code wasn’t changing much, but the preview boilerplate kept growing. So instead of creating several preview functions for the same composable, I created a single annotation file called DevicePreviews.kt, and now I annotate one preview function with @DevicePreviewsand get the whole matrix in one shot.</p><h3>Why I Stopped Writing One-Off Previews</h3><p>The simplest Compose preview setup is straightforward: create a composable, add @Preview, and Android Studio shows it in the design view with live updates as you edit. Compose also supports attaching multiple @Preview annotations to the same function so you can render several versions of that UI. One of the main benefits of this workflow is faster iteration without constantly launching an emulator.</p><p><a href="https://developer.android.com/develop/ui/compose/tooling/previews">Preview your UI with composable previews | Jetpack Compose | Android Developers</a></p><p>But once a screen becomes real UI instead of a toy example, that convenience can turn into a maintenance problem.</p><p>A mature screen usually needs to answer the same questions every time:</p><p>Will this still look right on a smaller phone?<br>Will it survive dark mode?<br>Will larger accessibility text break the layout?<br>Does this still make sense on a tablet?</p><p>When each of those checks becomes its own preview function, the file starts filling with boilerplate instead of signal. The UI implementation remains small, but the preview section becomes repetitive and noisy.</p><p>That duplication is exactly where custom multipreview annotations shine. Android Studio’s Compose tooling supports defining an annotation class that itself contains multiple @Preview annotations, and when you place that custom annotation on a composable, Studio renders all of the variants at once.</p><h3>The Compose Feature That Makes This Possible</h3><p>Compose preview tooling has supported this pattern for a while. Android Studio Dolphin introduced Compose multipreview annotations, which let developers wrap multiple @Preview definitions inside a reusable annotation class. Later, Compose also added official multipreview templates such as @PreviewScreenSizes, @PreviewFontScales, @PreviewLightDark, and @PreviewDynamicColors for common scenarios.</p><p>That means there are really two good ways to think about preview reuse:</p><p>You can use the built-in templates when the defaults match your needs, or you can create your own annotation when your team keeps checking the same custom set of cases over and over. The second option is what I wanted, because I wasn’t looking for a generic preview set. I wanted <em>my</em> review checklist encoded into one annotation.</p><p>That is the real advantage of a custom annotation: it turns preview configuration into a shared project convention instead of something every developer rewrites by hand.</p><h3>My DevicePreviews Annotation</h3><p>Here is the annotation I created:</p><pre>import android.content.res.Configuration<br>import androidx.compose.ui.tooling.preview.Preview<br><br>/**<br> * MultiPreview annotation that represents various device sizes and configurations.<br> * Use this to quickly see how a Composable looks on different screens.<br> */<br>@Preview(name = &quot;Small Phone&quot;, showBackground = true, widthDp = 320, heightDp = 640)<br>@Preview(name = &quot;Normal Phone&quot;, showBackground = true, widthDp = 360, heightDp = 800)<br>@Preview(name = &quot;Large Phone&quot;, showBackground = true, widthDp = 430, heightDp = 932)<br>@Preview(<br>    name = &quot;Dark Mode&quot;,<br>    showBackground = true,<br>    uiMode = Configuration.UI_MODE_NIGHT_YES,<br>    widthDp = 360,<br>    heightDp = 800<br>)<br>@Preview(<br>    name = &quot;Large Font&quot;,<br>    showBackground = true,<br>    fontScale = 1.5f,<br>    widthDp = 360,<br>    heightDp = 800<br>)<br>@Preview(name = &quot;Tablet Portrait&quot;, showBackground = true, widthDp = 800, heightDp = 1280)<br>@Preview(name = &quot;Tablet Landscape&quot;, showBackground = true, widthDp = 1280, heightDp = 800)<br>annotation class DevicePreviews</pre><p>What I like about this approach is that it stays brutally simple. There is no framework around it, no abstraction overhead, and no extra mental model for the rest of the team. It is just one Kotlin annotation class that groups the preview variants I care about most.</p><p>Under the hood, this is built from standard Compose preview parameters. widthDp and heightDp let you define preview dimensions directly in dp, fontScale lets you simulate larger text, and uiMode can use Configuration.UI_* constants such as Night Mode. Compose’s preview docs explicitly support these knobs as first-class @Previewparameters.</p><p>I also intentionally named it DevicePreviews in the plural. That small naming choice matters: it communicates that this annotation is not a single preview style, but a bundle of preview variants.</p><h3>How I Use It in Practice</h3><p>Once the annotation exists, the usage is exactly what I wanted from the beginning: one preview function, one annotation, many renderings.</p><pre>@DevicePreviews<br>@Composable<br>private fun ProfileCardPreview() {<br>    MyAppTheme {<br>        ProfileCard(<br>            name = &quot;Ada Lovelace&quot;,<br>            jobTitle = &quot;Android Engineer&quot;,<br>            isOnline = true<br>        )<br>    }<br>}</pre><p>That single function now produces every variant defined in DevicePreviews: phone sizes, dark mode, large font, and both tablet orientations. This is the same multipreview behavior documented by the official Compose tooling guidance: add the custom annotation once, and Android Studio renders each declared preview configuration for you.</p><p>This pattern works especially well when the preview composable is a clean UI entry point that takes state as input. The official guidance recommends defining screens in terms of the state they receive and the events they emit, because that makes them easier to preview and test.</p><p>That leads to a practical rule I now follow:</p><p>I do <strong>not</strong> try to preview the composable that directly creates a ViewModel. Instead, I preview the stateless screen or content composable underneath it. Android’s preview docs explicitly warn that previews cannot reliably construct ViewModel dependencies, especially when repositories, managers, use cases, or dependency injection are involved. The recommended pattern is to pass sample state into another composable and preview that instead.</p><p>And if I want multiple content states on top of multiple devices, I don’t explode the annotation with business-state variants. I keep @DevicePreviews focused on device and configuration checks, and I use @PreviewParameter when I need sample data variations. Compose supports that too, rendering one preview per provided sample value.</p><h3>Why This Scales Better Than Separate Preview Functions</h3><p>The biggest win here is not that the code is shorter. The biggest win is that the preview strategy becomes consistent.</p><p>When every developer writes their own preview setup, small differences creep in. One person checks dark mode but forgets large font. Another checks phone sizes but skips tablet. Another duplicates nearly the same set of previews with slightly different dimensions. Over time, your preview coverage becomes uneven even though everyone is technically “using previews.”</p><p>A shared annotation solves that by turning preview expectations into a reusable default. If a composable should pass the same visual checks as the rest of the app, I just add @DevicePreviews and move on.</p><p>There is also a subtle but useful Compose detail worth understanding if you extend this pattern later. The official docs note that when you combine multiple multipreview annotations and normal preview annotations, Android Studio does <strong>not</strong> generate every possible combination. Each annotation renders only its own variants independently.</p><p>That means if I later create something like @LocalePreviews or add a separate @Preview(locale = &quot;fa&quot;), I should not expect an automatic Cartesian product of device × font × theme × locale. If I truly need that full matrix, I should build it intentionally rather than assuming Compose will expand everything for me. That is not a limitation of my annotation; it is how multipreview composition is designed to work.</p><p>In practice, I actually like this behavior. It keeps previews readable and prevents Studio from trying to render an absurd number of variants for every screen.</p><h3>A Few Caveats Worth Knowing</h3><p>Compose previews are fast because Android Studio renders them with Layoutlib, a version of the Android framework that runs inside the IDE rather than on a real device. That is why previews feel lightweight, but it also explains their limits: no network access, no file access, and some Context APIs may not be fully available.</p><p>So @DevicePreviews is best seen as a UI verification tool, not a substitute for device testing. It is perfect for layout sanity checks, theming, text scaling, and form-factor inspection. It is not the place to prove that your real data loading, permissions flow, or platform integrations are fully correct.</p><p>The good news is that Android Studio also lets you run a specific @Preview on an emulator or physical device. The catch is that preview annotation arguments like widthDp and locale are not applied when that preview is deployed as a runnable activity, so you should treat that run mode as a separate step for functional sanity checks rather than a literal deployment of your preview matrix.</p><p>Another nice detail: every rendered preview can be copied as an image directly from Android Studio. That makes previews unexpectedly useful for PR discussions, UI reviews, and lightweight design communication.</p><h3>The Real Lesson Behind This Pattern</h3><p>What I like most about this little refactor is that it changed the role of previews in my project.</p><p>Instead of thinking of previews as throwaway snippets attached to individual composables, I started treating them as a reusable quality checklist. Compose already supports custom multipreview annotations, and it also ships official templates for common scenarios. My @DevicePreviews annotation is just a project-specific version of the same idea: turn repeated visual checks into one reusable tool.</p><p>So if your preview files are filling up with functions like SmallPhonePreview, DarkPreview, TabletPreview, and LargeFontPreview, consider stopping for a minute and asking a better question:</p><p>What if all of those were really just one annotation?</p><p>For me, that answer was @DevicePreviews — and it made my Compose preview workflow cleaner, faster, and easier to keep consistent across the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cf18732c270" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>