compose-state-holder-ui-split

vitorpamplona/amethyst

Ревью экранных composable с ViewModel, сбором состояния и навигацией.

Звёзды1 624
Авторvitorpamplona

Установка

SKILL.md

Compose: state holder/UI split

Core principle

Separate state-holder wiring from UI rendering. The state-holder composable talks to ViewModels, components, flows, navigation, and side effects. The UI composable takes plain immutable UI state plus callbacks and describes layout.

This keeps screens previewable, testable, and easier to reuse across Android, Desktop, TV, and KMP/CMP targets.

When to use this skill

Use this when a Compose screen:

  • Takes a ViewModel, component, controller, navigator, repository, or service directly.
  • Collects app/business state or side effects in the same function that lays out most UI.
  • Passes a whole state holder into child composables instead of explicit state and callbacks.
  • Is hard to preview because it needs dependency injection, navigation, lifecycle, or fake services.
  • Has UI tests that must construct a full app stack to verify a simple layout branch.

The pattern

Use a small public state-holder composable:

@Composable
fun ProfileScreen(component: ProfileComponent, modifier: Modifier = Modifier) {
    val state by component.state.collectAsStateWithLifecycle()

    ProfileScreen(
        state = state,
        onNameChange = component::onNameChange,
        onSaveClick = component::save,
        onBackClick = component::back,
        modifier = modifier,
    )
}

Then put UI in a plain composable that knows nothing about the state holder:

@Composable
fun ProfileScreen(
    state: ProfileUiState,
    onNameChange: (String) -> Unit,
    onSaveClick: () -> Unit,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    ProfileContent(
        name = state.name,
        isSaving = state.isSaving,
        canSave = state.canSave,
        onNameChange = onNameChange,
        onSaveClick = onSaveClick,
        onBackClick = onBackClick,
        modifier = modifier,
    )
}

Private content functions can break up layout:

@Composable
private fun ProfileContent(
    name: String,
    isSaving: Boolean,
    canSave: Boolean,
    onNameChange: (String) -> Unit,
    onSaveClick: () -> Unit,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    // Layout only.
}

Rules of thumb

ConcernState-holder composableUI composable
Collect ViewModel/component stateYesNo
Collect one-shot effectsYes, or a tiny sibling effect handlerUsually no
Hold dependency-injected objectsYesNo
Accept immutable UI stateUsually passes it throughYes
Accept lambdas for user eventsWires themCalls them
Own layout, modifiers, semantics, test tagsNo/minimalYes
Own UI-local state like scroll, focus, text input, animation, interactionSometimes seeds itYes
Preview/screenshot friendlyNot necessarilyYes

The "no collection in UI composables" rule is about app/business state and side-effect streams. Plain UI composables can still own UI-local framework state: rememberScrollState, rememberLazyListState, FocusRequester, focus state, animation state, TextFieldState, MutableInteractionSource.collectIsPressedAsState(), and similar behavior that belongs to the rendered widget.

If that UI-local state grows into coordinated behavior with multiple related fields and operations, consult compose-expert (state hoisting section) to decide whether it should become a plain state holder class remembered in composition.

What to pass

Pass the smallest useful UI contract:

  • Prefer a dedicated UiState/State object over many unrelated primitives when the screen has real state.
  • Prefer explicit lambdas (onRetryClick, onItemSelected) over passing a whole component.
  • Keep domain models out of the UI composable if they force business rules into UI. Map to UI models when the UI needs a different shape.
  • Keep navigation as callbacks. The UI composable says "user clicked back", not "navigate to route X".
  • Frame-rate or UI-local values that should not force whole-tree recomposition when they change: prefer provider lambdas and deferred reads per compose-state-deferred-reads.

Side effects

compose-side-effects covers effect APIs (LaunchedEffect, DisposableEffect, SideEffect), keys, cleanup, and rememberUpdatedState.

Handle effects near the state holder, where the effect source and imperative target are both available:

@Composable
fun ProfileScreen(component: ProfileComponent, snackbarHostState: SnackbarHostState) {
    val state by component.state.collectAsStateWithLifecycle()

    LaunchedEffect(component) {
        component.effects.collect { effect ->
            when (effect) {
                ProfileEffect.Saved -> snackbarHostState.showSnackbar("Saved")
            }
        }
    }

    ProfileScreen(state = state, onSaveClick = component::save)
}

If effect handling grows, extract ProfileEffects(component, snackbarHostState) rather than pushing the component into the UI composable.

Common mistakes

MistakeWhy it hurtsFix
fun Screen(viewModel: MyViewModel) contains all layoutHard to preview/test without Android lifecycle and DIAdd a plain UI overload that takes state and callbacks
Child composables take componentDependencies leak through the treePass only the state/callbacks that child needs
UI composable launches navigationUI becomes coupled to app routingExpose onBackClick, onItemClick, etc.
UI composable collects app/business flowsCollection lifecycle is hidden in layoutCollect near the state holder and pass values down
UI-local state is hoisted into the state holder for no reasonState holder starts owning layout mechanicsKeep scroll/focus/animation/text-field interaction state in the UI composable when it is only UI behavior
Every tiny composable gets a state-holder overloadToo much ceremonySplit at screen/section boundaries, not every Row

When NOT to apply

  • Tiny one-off composables that already take plain values and callbacks.
  • Design-system primitives such as Button, Card, or ListItem; those should expose slots and modifiers, not state holders.
  • Cases where the state-holder composable would only forward one primitive and add no isolation.

Related

  • compose-expert — Amethyst's shared-UI patterns, including state hoisting for UI element state and plain state holder classes.
  • compose-side-effects — effect keys and cleanup in Compose.
  • compose-state-deferred-reads — deferred reads for frame-rate / UI-local values passed across boundaries.
  • kotlin-multiplatform — platform services, native views, and expect/interface boundaries when shared UI meets platform-specific leaves.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: compose-state-holder-ui-split](https://darkplay.ru/ai/skills/vitorpamplona-amethyst-compose-state-holder-ui-split)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★
ui-ux-pro-maxnextlevelbuilder · Профессиональные знания по UI/UX-дизайну для ИИ-ассистентов программирования. Включает…
151 010 ★
Ux Designershanraisshan · Создаёт краткий и понятный UX-бриф с потоками, состояниями и аннотациями.
61 912 ★
cli-anythinghkuds · Создавайте мощные CLI-интерфейсы с сохранением состояния для любого GUI-приложения по…
5 комп.
expoanthropics · Официальные навыки Expo для создания, развёртывания, обновления и отладки приложений…
100 комп.
mcp-tunnelsanthropics · Подключение Claude к приватному MCP-серверу через туннель Anthropic MCP. Команда…
100 комп.
project-artifactanthropics · Создание и публикация живой страницы статуса проекта — обзор и критерии успеха…
100 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8