Logotipo de Compose State Hoisting

Compose State Hoisting

Comunidad
alexandru
compose-state-hoisting

Compose state management with a strong state-hoisting preference for Kotlin Compose (Android, Multiplatform, Compose for Web). Use for refactors or new UI that needs clear state ownership, unidirectional data flow, saved state decisions, or guidance on remember/retain/rememberSaveable/rememberSerializable, and for designing stateless composables with event callbacks.

Descripción general

Editoralexandru
Repositorioskills
Nombre de la habilidadcompose-state-hoisting
Estrellas
51
Forks
3
Archivos incluidos
1
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Archivos incluidos: 1

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por alexandru en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Compose State Hoisting en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/alexandru/skills/tree/main/skills/coding/compose-state-hoisting
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/alexandru/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/skills/coding/compose-state-hoisting .claude/skills/compose-state-hoisting
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Compose State Hoisting en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Compose State Hoisting automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Compose State Hoisting no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Compose State Hoisting

Overview

Apply state hoisting and unidirectional data flow to Compose UIs, choosing the right state owner, lifespan, and saving strategy.

For condensed reference and examples, see references/compose-state-guidance.md.

Workflow

  1. Identify the state and the logic that reads/writes it.
  2. Decide the state owner (lowest common ancestor; or a plain state holder class, or a screen-level state holder like Android ViewModel for complex UI/business logic).
  3. Choose the lifespan API (remember/retain/rememberSaveable/rememberSerializable) based on how long it must survive.
  4. Make UI composables stateless: pass value and event callbacks; state goes down, events go up.
  5. Decide what must be saved and how (rememberSaveable, SavedStateHandle, or platform storage).
  6. Verify that state and callbacks are not duplicated or leaked.

Rules of thumb

  • Hoist state to the lowest common ancestor of all readers/writers.
  • Keep composables stateless: state down, events up.
  • Pick the lifespan API explicitly; default to remember only for ephemeral UI state.
  • Save minimal data and rehydrate anything larger or derived.

Decision hints

  • If multiple parts of the UI must read/write the same state, hoist it.
  • If state survives config changes or process death, choose retain or rememberSaveable and document why.
  • For business logic, use a screen-level state holder; do not pass it down the tree.

Common pitfalls

  • Duplicated state owners causing divergence.
  • Over-saving large objects in rememberSaveable/SavedStateHandle.
  • Mixing remember and retain for the same object.

State Hoisting Rules

  • Hoist state to the lowest common ancestor of all composables that read and write it; keep it as close to consumers as possible.
  • If multiple states change from the same events, hoist them together.
  • Over-hoisting (e.g., hoisting to screen level when a subtree would suffice) is acceptable and safer than under-hoisting; under-hoisting breaks unidirectional flow and creates duplicate sources of truth. Over-hoisting may trigger more recompositions or lose state on navigation.
  • Prefer exposing immutable state plus event callbacks from the state owner.

Stateless vs Stateful Composables

  • Provide a stateless API: value: T and onValueChange: (T) -> Unit (or more specific event lambdas).
  • Keep state internal only if no other composable needs to read or change it and the UI logic is simple.
  • Offer both stateful and stateless variants when useful; the stateless version is the reusable/testable one.

Decide Where to Hoist

  • UI element state + simple UI logic: keep internal or hoist within the UI subtree.
  • Complex UI logic: move state and UI logic into a plain state holder class scoped to the Composition.
  • Business logic or screen UI state: hoist to a screen-level state holder (Android: ViewModel; Multiplatform: platform-specific or library solutions like Circuit, Molecule). Do not pass screen-level state holders down the tree; inject at the screen level and pass state/events instead.
  • Deep prop drilling: for state needed by many distant descendants (theme, user session), consider CompositionLocal to avoid passing parameters through many layers. Use sparingly; prefer explicit parameter passing when practical.

Choose the Correct Lifespan

  • remember: survives recomposition only; same instance. Use for composition-scoped objects and small internal UI state. Do not use for user input that must be preserved.
  • retain: survives recomposition + window/configuration changes (Android: activity recreation), not process death. Use for non-serializable objects (players, caches, flows, lambdas). Do not retain platform-specific lifecycle objects (Android: Activity, View, Fragment, ViewModel, Context, Lifecycle). Do not retain objects that were already created with remember by the caller—retain and remember are mutually exclusive for the same object.
  • rememberSaveable / rememberSerializable: survives recomposition + configuration changes + process death (Android) by saving to the platform's saved state mechanism (Android: Bundle; other platforms may vary). Use for user input or UI state that cannot be reloaded from another source. Restored objects are equal but not the same instance.

Remember Keys: Control when state resets by passing keys to remember(key1, key2) { }. State recreates when any key changes. Omit keys only when state should survive all recompositions.

Saving UI State

  • Use rememberSaveable for UI state hoisted in composables or plain state holders; save only minimal, small data.
  • Saved state storage is limited (Android Bundle: ~1MB); do not store large objects or lists. Store IDs/keys and rehydrate from data/persistent storage.
  • Android: Use SavedStateHandle in a ViewModel for UI element state that must survive process death; keep it small and session-scoped (not persistent app data).
  • Do not save full screen UI state; rebuild it from the data layer on restoration.

Observable Types in Compose

  • Convert observable types to State<T> before reading in composables.
  • Flow: use collectAsState (platform-agnostic, always collects) or collectAsStateWithLifecycle (Android only, lifecycle-aware, pauses collection when UI is not visible).
  • LiveData (Android): use observeAsState.
  • For custom observables, create a State<T> via produceState.

State Callbacks (RememberObserver / RetainObserver)

  • Run initialization side-effects in onRemembered / onRetained, not in constructors or remember/retain lambdas.
  • Always cancel work in onForgotten / onRetired; handle onAbandoned for canceled compositions.
  • Keep implementations private; expose safe factory functions like rememberX() to avoid misuse.
  • Do not remember the same object twice; do not pass parameters that are already wrapped in State<T> to another remember call—this creates unnecessary nested observability.

Common Anti-Patterns

  • Storing mutable collections or mutable data classes directly as state; prefer immutable containers wrapped in State or use snapshot state collections (mutableStateListOf, mutableStateMapOf).
  • Duplicating state in multiple owners instead of hoisting to a single source of truth.
  • Mixing remember and retain for the same object; remembering/retaining objects with mismatched lifespans.
  • Saving large or complex objects in rememberSaveable/SavedStateHandle (Android); save IDs and rehydrate instead.
  • Computing derived values inside composables without derivedStateOf, causing unnecessary recompositions.

Output Expectations

  • Favor stateless composables with value + callbacks.
  • Prefer lowest common ancestor hoisting.
  • Choose lifecycle APIs intentionally; call out saving strategy explicitly.
  • Keep state minimal, immutable, and observable.

References

  • Load references/compose-state-guidance.md for decision trees, tables, and code examples.

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Son archivos de solo lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA Compose State Hoisting?

Compose state management with a strong state-hoisting preference for Kotlin Compose (Android, Multiplatform, Compose for Web). Use for refactors or new UI that needs clear state ownership, unidirectional data flow, saved state decisions, or guidance on remember/retain/rememberSaveable/rememberSerializable, and for designing stateless composables with event callbacks.

¿Por qué usar Compose State Hoisting en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Compose State Hoisting está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Compose State Hoisting en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/alexandru/skills/tree/main/skills/coding/compose-state-hoisting. TypingMind lee el archivo SKILL.md de esa carpeta, empaqueta los archivos de la carpeta e instala el conjunto como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Compose State Hoisting?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Compose State Hoisting?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Compose State Hoisting con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Compose State Hoisting?

alexandru la ha publicado en GitHub. Consulta el repositorio para conocer las condiciones de la licencia. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇