# Learning Kotlin and Compose through React

I came to an Android app knowing React and TypeScript, Node, Laravel and Python, and about two weeks of Kotlin. So the skill I wrote for it tells Claude who the developer is and to explain everything through React. The same file holds the app's architecture rules.

Its centre is a mapping table, and the useful column is "Watch out", the place where the React habit goes wrong. A few rows:

| React/TS | Compose/Kotlin | Watch out |
|---|---|---|
| `useState` | `remember { mutableStateOf(x) }` | `rememberSaveable` if it must survive rotation or process death |
| `useCallback` | usually unnecessary | Lambdas are cheap; stability matters more than identity |
| Redux/Zustand store | ViewModel + `StateFlow` | One ViewModel per screen |
| `async/await` | `suspend` + coroutines | Calling a `suspend fun` is the await |

Save it as `.claude/skills/kotlin-for-react-devs/SKILL.md` and rewrite the first paragraph to describe yourself. The house rules (MVVM-lite, no DI framework, writes only through a repository) are the app's, for a small single-module codebase; replace them with yours. The original also covered the app's alarm engine, which I left out.

````markdown
---
name: kotlin-for-react-devs
description: Project architecture conventions (MVVM-lite, no DI framework, unidirectional data flow) and Kotlin/Compose patterns explained through the developer's React/TypeScript mental model. Use when writing ViewModels, composables, state management or coroutines, or when structuring a new screen or data flow.
---

# Kotlin/Compose through a React lens, plus this project's conventions

The developer is strong in React/TS, Node, Laravel and Python, and new to Kotlin/Compose.
Explanations land best mapped from that stack. These are also the house rules: deviating from
the architecture below needs a reason stated in the PR.

## The mapping

| React/TS | Compose/Kotlin | Watch out |
|---|---|---|
| Component | `@Composable fun` | Functions, not classes; no instances |
| `useState` | `remember { mutableStateOf(x) }` | `rememberSaveable` if it must survive rotation/process death |
| Props | function parameters | Pass values + event lambdas ("state down, events up") |
| `useEffect(fn, [deps])` | `LaunchedEffect(deps) { }` | Relaunches when keys change |
| `useEffect` cleanup | `DisposableEffect { onDispose { } }` | |
| `useMemo` | `derivedStateOf` / `remember(key) { }` | Only for expensive derivations |
| `useCallback` | usually unnecessary | Lambdas are cheap; stability matters more than identity |
| Context | `CompositionLocal` | Theme/locale level only |
| `key` prop in lists | `items(list, key = { it.id })` | Always key `LazyColumn` items |
| Redux/Zustand store | ViewModel + `StateFlow` | One ViewModel per screen |
| `async/await` | `suspend` + coroutines | Calling a `suspend fun` is the await |
| `Promise.all` | `coroutineScope { awaitAll(async{}, …) }` | |

Recomposition ≈ re-render: composables re-run when the state they read changes. Same hygiene
as React: no side effects in the function body (use effect APIs), derive don't duplicate,
key your lists.

## MVVM-lite: one pattern for every screen

Room `Flow` → ViewModel `StateFlow` → Compose. UI never touches DAOs; the ViewModel never
touches Compose types.

```kotlin
class ItemsViewModel(private val repo: ItemRepository) : ViewModel() {
    val items: StateFlow<List<Item>> =
        repo.stream()
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun onSave(item: Item) = viewModelScope.launch { repo.save(item) }
}

@Composable
fun ItemsScreen(vm: ItemsViewModel) {
    val items by vm.items.collectAsStateWithLifecycle()
    ItemsContent(items, onSave = vm::onSave)   // stateless, previewable
}
```

House rules:
- Each screen is a thin stateful `XScreen` (collects state, binds the VM) plus a stateless
  `XContent` (values in, events out), like presentational components.
- Events go up as lambdas; don't pass the ViewModel deep down the tree.
- `collectAsStateWithLifecycle()`, not plain `collectAsState()`: it stops collecting when
  the app is in the background.
- Room DAOs return `Flow` or are `suspend`. `allowMainThreadQueries()` is banned.
- All writes go through the repository, never DAOs directly.

## No DI framework: manual wiring

One `AppContainer` built in `Application.onCreate()`; ViewModels get dependencies through a
small factory. A hand-rolled composition root instead of an IoC container: at single-module
size, Hilt buys ceremony, not value.

```kotlin
class App : Application() {
    lateinit var container: AppContainer
    override fun onCreate() { super.onCreate(); container = AppContainer(this) }
}

class AppContainer(app: Application) {
    val db = AppDb.build(app)
    val repo = ItemRepository(db.itemDao())
}
```

Receivers, services and workers reach it through
`(context.applicationContext as App).container`.

## Coroutines

- `viewModelScope.launch { }` ≈ an async task tied to the screen's lifetime; cancelled with it.
- `withContext(Dispatchers.IO)` only for blocking IO outside Room (files). Room and DataStore
  are already main-safe.
- Cancellation is cooperative: long loops between suspension points check `isActive`. The
  nearest React-world idea is AbortController, built into the type system.

## Kotlin idioms worth adopting early

- `data class` + `sealed interface` for UI state ≈ discriminated unions in TS. Model
  Loading/Content/Error as a sealed hierarchy and `when` over it exhaustively.
- `?.` and `?:` ≈ optional chaining and nullish coalescing.
- `apply`/`let`/`also` are ergonomic lambdas; don't nest them more than one deep.
- Prefer `val` + `copy()`, the same instinct as spreading state in React.

## Build hygiene

- Version catalog (`gradle/libs.versions.toml`) from day one; the Compose BOM pins Compose versions.
````

see also: [Wsl2 Adb Skill](/articles/wsl2-adb-skill)
