Skip to main content

Avoid Passing ViewModels in Composables – Here's Why

Jetpack Compose has revolutionized Android UI development by providing a declarative and reactive approach to building user interfaces. One of its key promises is simplicity, but developers often find themselves facing questions about architecture and best practices—one of which is whether to pass ViewModel instances directly into composables.

While it might seem convenient to do so, passing ViewModels into composables can lead to a host of issues that undermine the principles of Compose and modern Android development. In this blog post, we will explore why this practice should be avoided, the potential pitfalls, and better alternatives to ensure clean, maintainable, and testable code.

Understanding Jetpack Compose’s Principles

Before diving into why passing ViewModels in composables is discouraged, it’s essential to understand the core principles of Jetpack Compose:

  1. Declarative UI: Compose uses a declarative approach, where the UI is defined as a function of the current state.

  2. Unidirectional Data Flow (UDF): The flow of data should be predictable and follow a one-way direction—from state to UI.

  3. Separation of Concerns: UI logic should be distinct from business logic to ensure modularity and reusability.

When you pass ViewModels into composables, you risk violating one or more of these principles. Let’s delve deeper into the reasons.

Why Passing ViewModels in Composables is Problematic

1. Coupling UI with Business Logic

ViewModels are primarily designed to encapsulate business logic and serve as the source of truth for UI state. When a ViewModel is passed into a composable, the composable becomes tightly coupled to that specific ViewModel implementation. This makes the composable less reusable and harder to test.

Example of Tight Coupling:

@Composable
fun ProfileScreen(viewModel: ProfileViewModel) {
    val profileState = viewModel.profileState.collectAsState()
    // UI rendering based on profileState
}

Here, ProfileScreen can only function with ProfileViewModel. Reusing this composable in another context without the same ViewModel becomes a challenge.

2. Violating the Separation of Concerns

Composables should focus on rendering UI based on state. When a ViewModel is passed in, it becomes responsible for both state management and UI logic, blurring the lines between these layers. This violates the separation of concerns and makes your codebase harder to maintain.

3. Testing Challenges

Composables that depend on ViewModels are harder to test in isolation. Unit testing composables should involve verifying their behavior based on the input state, not the implementation details of a ViewModel.

Example of a Difficult-to-Test Composable:

@Composable
fun Dashboard(viewModel: DashboardViewModel) {
    val data = viewModel.dashboardData.collectAsState()
    // Render UI
}

Testing the Dashboard composable now requires mocking the DashboardViewModel, adding unnecessary complexity.

4. Lifecycle Management Issues

ViewModels are lifecycle-aware, scoped to their respective ViewModelStoreOwner (e.g., Activity or Fragment). Passing ViewModels into composables can create confusion about their lifecycle, leading to potential bugs such as:

  • Memory leaks

  • Unexpected behavior when composables are recomposed or moved across lifecycle boundaries

Better Alternatives to Passing ViewModels

1. Use remember and state hoisting

Instead of passing ViewModels directly, pass the state and event handlers managed by the ViewModel. This keeps the composable independent of the ViewModel while still leveraging its functionality.

Example of State Hoisting:

@Composable
fun ProfileScreen(
    profileState: ProfileState,
    onEvent: (ProfileEvent) -> Unit
) {
    // UI rendering based on profileState
    Button(onClick = { onEvent(ProfileEvent.LoadProfile) }) {
        Text("Load Profile")
    }
}

// ViewModel usage
val profileState by viewModel.profileState.collectAsState()
ProfileScreen(
    profileState = profileState,
    onEvent = { viewModel.handleEvent(it) }
)

This approach keeps ProfileScreen focused on UI rendering and decoupled from the ViewModel.

2. Leverage rememberViewModel

For cases where a composable must access a ViewModel, use hiltViewModel or viewModel() inside the composable to obtain the instance. This ensures the ViewModel lifecycle is properly managed by Compose.

Example:

@Composable
fun DashboardScreen() {
    val viewModel: DashboardViewModel = hiltViewModel()
    val dashboardState by viewModel.dashboardData.collectAsState()

    DashboardContent(dashboardState)
}

@Composable
fun DashboardContent(state: DashboardState) {
    // Render UI
}

By isolating the ViewModel instantiation to the top-level composable, you avoid passing it down the composable tree.

3. Encapsulate Logic in Use Cases or Repositories

Instead of placing all logic in the ViewModel, delegate it to use cases or repositories. Pass the resulting state to composables.

Example:

val profileState = getProfileUseCase().collectAsState()
ProfileScreen(profileState)

This approach promotes a clean architecture and ensures composables remain focused on UI concerns.

Common Questions and Misconceptions

Q: Doesn’t this add boilerplate?

A: While it may seem like additional effort, state hoisting and proper separation of concerns reduce technical debt and improve the maintainability of your codebase in the long term.

Q: What if I need to access ViewModel in deeply nested composables?

A: Use dependency injection tools like Hilt to provide dependencies closer to where they are needed. Alternatively, pass state and event handlers down the tree instead of the entire ViewModel.

Q: Isn’t this overkill for small projects?

A: Even in small projects, following best practices ensures scalability and ease of maintenance as the project grows.

Final Thoughts

Passing ViewModels into composables may seem convenient, but it often leads to tightly coupled, hard-to-test, and error-prone code. By leveraging state hoisting, remember, and clean architecture principles, you can build Compose applications that are modular, testable, and maintainable.

Jetpack Compose encourages developers to think declaratively and embrace unidirectional data flow. Avoiding the direct use of ViewModels in composables is a step towards aligning with these principles and unlocking the full potential of Compose.

By following the strategies outlined in this post, you can ensure your applications are robust, scalable, and developer-friendly.

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...