Logotipo de Choosing Derivedstateof

Choosing Derivedstateof

Comunidad
skydoves
choosing-derivedstateof

Usa esta habilidad para decidir cuándo derivedStateOf de Jetpack Compose es la herramienta adecuada y cuándo solo añade sobrecarga. Explica la regla «la frecuencia de entrada debe superar la frecuencia de salida», el envoltorio obligatorio remember { derivedStateOf { } }, el problema habitual de capturar variables que no son de estado con su valor inicial (y la solución remember(key)) y la alternativa snapshotFlow para efectos secundarios sin espera basados en valores derivados. Úsala cuando el desarrollador mencione derivedStateOf, valores booleanos determinados por la posición de desplazamiento, comprobaciones de umbral, firstVisibleItemIndex, «mostrar FAB al desplazarse», recuentos de recomposición que no bajan después de envolver un valor o pregunte si una concatenación de cadenas calculada debería usar derivedStateOf.

Add to TypingMind

Descripción general

Editorskydoves
Repositoriocompose-performance-skills
Nombre de la habilidadchoosing-derivedstateof
Estrellas
515
Forks
19
Archivos incluidos
Solo instrucciones
LicenciaApache-2.0
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.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

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

Instalación

Instala la habilidad de IA Choosing Derivedstateof 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/skydoves/compose-performance-skills/tree/main/recomposition/choosing-derivedstateof
  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/skydoves/compose-performance-skills.git /tmp/compose-performance-skills
mkdir -p .claude/skills
cp -r /tmp/compose-performance-skills/recomposition/choosing-derivedstateof .claude/skills/choosing-derivedstateof
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Choosing Derivedstateof 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 Choosing Derivedstateof 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 Choosing Derivedstateof 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á.

Choosing derivedStateOf — Filter Hot Inputs into Cold Outputs

derivedStateOf produces a State whose readers only invalidate when the derived result changes, even if the input states change far more often. Use it when input frequency exceeds output frequency. Use it for any other shape and it is pure overhead — an extra snapshot subscription with no filtering benefit. This skill teaches Claude when to reach for it, when to refuse, and how to avoid the canonical capture-by-initial-value pitfall.

When to use this skill

  • The developer asks whether a value should be wrapped in derivedStateOf.
  • A scroll position drives a boolean (firstVisibleItemIndex == 0, scrollState.value > threshold, "show FAB on scroll").
  • A high-frequency input (drag delta, animation progress) feeds a low-frequency output (boolean threshold, bucketed integer).
  • A derivedStateOf exists in the code but recomposition counts didn't drop, or the value never updates after the first composition (the capture-by-initial-value bug).
  • The developer wants a one-shot side effect (analytics, logging, snackbar) when a derived value flips.

When NOT to use this skill

  • The state read is in the wrong phase (e.g. Modifier.alpha(state.value)). Fix that with ../deferring-state-reads/SKILL.md first — derivedStateOf does not address phase issues.
  • Diagnosing whether a parameter is unstable. That is ../../stability/diagnosing-compose-stability/SKILL.md.
  • Input frequency equals output frequency (e.g. "$first $last" from two name states). derivedStateOf is pure overhead in that case — use a direct read or a plain remember.

Prerequisites

  • Familiarity with state-read-driven recomposition: a snapshot read inside a restartable composable subscribes that composable's restart scope to the state.
  • Compose runtime ≥ 1.0 (the API is foundational; behavior described here is stable).
  • Ability to confirm recomposition counts via Layout Inspector or @TraceRecomposition from skydoves/compose-stability-analyzer.

Workflow

  • 1. Identify the input state(s) and the value the UI actually consumes. Write down both update frequencies. Example: listState.firstVisibleItemIndex (changes every list item scrolled past) → Boolean (changes once when the user crosses index 0).

  • 2. Compare frequencies. Apply the rule:

    • Input updates much more often than output → derivedStateOf is the right tool.
    • Input and output update at roughly the same rate → derivedStateOf adds an extra snapshot subscription for nothing. Use a direct read or a plain remember(input1, input2).
  • 3. Wrap the derivation in remember { derivedStateOf { … } }. A bare derivedStateOf { } would be re-created on every composition, defeating the cache. The remember is mandatory.

  • 4. If the lambda captures non-state variables (function parameters, locals, props), pass them as remember keys. A captured non-state variable is read once at first composition and frozen forever — the derivation will silently use the stale value. The fix is remember(threshold) { derivedStateOf { … > threshold } }.

  • 5. For one-shot side effects on a derived value (logging, analytics, snackbar), prefer snapshotFlow { … }.collect { … } inside LaunchedEffect. That avoids subscribing the composable's restart scope to the derived state; the side effect runs in a coroutine, off the composition path.

  • 6. Verify in Layout Inspector / @TraceRecomposition. The consuming composable's recomposition count MUST only increment when the derived result changes — not on every input tick. If it still climbs per input tick, either (a) the derivedStateOf is missing, (b) the remember is missing, or (c) something else (a sibling state read, a wrong-phase modifier) is invalidating the same scope.

Patterns

Pattern: scroll-to-top FAB — input >> output

kotlin
// WRONG
val showFab = listState.firstVisibleItemIndex > 0
// WRONG because: this reads firstVisibleItemIndex on every recomposition; the consuming composable invalidates per scrolled item, not just when the boolean flips.
kotlin
// RIGHT
val showFab by remember {
    derivedStateOf { listState.firstVisibleItemIndex > 0 }
}

firstVisibleItemIndex updates on every list item scrolled past; showFab only flips when the user crosses index 0. The remember keeps the derived state alive across compositions; the derivedStateOf filters out every input change that does not flip the boolean.

Pattern: pure overhead — input ≈ output

kotlin
// WRONG
val first by remember { mutableStateOf("Ada") }
val last by remember { mutableStateOf("Lovelace") }
val fullName by remember { derivedStateOf { "$first $last" } }
// WRONG because: first and last change at the same rate as fullName; derivedStateOf adds a snapshot subscription with zero filtering benefit.
kotlin
// RIGHT — direct read, no derivedStateOf needed
val first by remember { mutableStateOf("Ada") }
val last by remember { mutableStateOf("Lovelace") }
val fullName = "$first $last"

If a memoization cost concern exists (the concatenation is expensive), use remember(first, last) { computeFullName(first, last) } — derivedStateOf is still the wrong shape because there is nothing to filter.

Pattern: captured non-state variable — the silent bug

kotlin
// WRONG
@Composable
fun Header(threshold: Int, listState: LazyListState) {
    val isLarge by remember {
        derivedStateOf { listState.firstVisibleItemIndex > threshold }
    }
    // WRONG because: threshold is captured inside remember { ... } at first composition; later threshold changes are ignored, and the derivation reuses the stale value forever.
}
kotlin
// RIGHT — threshold is a remember key, so a new derivedStateOf is created when it changes
@Composable
fun Header(threshold: Int, listState: LazyListState) {
    val isLarge by remember(threshold) {
        derivedStateOf { listState.firstVisibleItemIndex > threshold }
    }
}

The rule: any non-State value captured by the derivedStateOf lambda MUST be a key on the surrounding remember. Otherwise the derivation locks in the value from first composition.

Pattern: one-shot side effect → snapshotFlow

kotlin
// WRONG
@Composable
fun Feed(listState: LazyListState, onScrolledPastFold: () -> Unit) {
    val pastFold by remember {
        derivedStateOf { listState.firstVisibleItemIndex > 5 }
    }
    if (pastFold) onScrolledPastFold()
    // WRONG because: side effects in a composable body run on every (re)composition, can fire multiple times for the same flip, and tie the side effect to the composition lifecycle.
}
kotlin
// RIGHT — fire-and-forget side effect via snapshotFlow
@Composable
fun Feed(listState: LazyListState, onScrolledPastFold: () -> Unit) {
    LaunchedEffect(listState) {
        snapshotFlow { listState.firstVisibleItemIndex > 5 }
            .distinctUntilChanged()
            .filter { it }
            .collect { onScrolledPastFold() }
    }
}

snapshotFlow reads snapshot state inside a coroutine and emits when the read-set's combined value changes. The LaunchedEffect keys the collection to listState, and distinctUntilChanged() ensures one emission per flip. No restart scope is involved — the consuming composable never recomposes for this signal.

Pattern: derive across many inputs to one bucket

kotlin
// RIGHT
val priceBucket by remember {
    derivedStateOf {
        when {
            cartTotal.value < 10_000 -> Bucket.Small
            cartTotal.value < 50_000 -> Bucket.Medium
            else -> Bucket.Large
        }
    }
}

cartTotal may tick by single won/cents; priceBucket flips at most twice across the entire range. This is the canonical use case.

Mandatory rules

  • MUST wrap every derivedStateOf in remember { … }. A bare derivedStateOf { } is re-created every composition and provides no filtering.
  • MUST add captured non-state variables (function parameters, local vals, props) as remember keys. Otherwise the derivation freezes the values from first composition.
  • MUST NOT use derivedStateOf when input and output frequency match. It is pure overhead; use a direct read or remember(keys) { … }.
  • MUST NOT wrap the result of collectAsState() / collectAsStateWithLifecycle() in derivedStateOf "just to be safe" — that adds a subscription layer for nothing. Filter upstream with .distinctUntilChanged() or .map { } on the flow.
  • PREFERRED: snapshotFlow { … } over derivedStateOf for fire-and-forget side effects. It keeps the composition free of the signal entirely.
  • PREFERRED: measure recomposition counts before AND after the change. The whole point of derivedStateOf is to reduce them; if they didn't drop, something else is wrong (often a wrong-phase read — see ../deferring-state-reads/SKILL.md).

Verification

  • Layout Inspector shows the consuming composable recomposes only when the derived result changes (e.g. once when the FAB appears, once when it disappears) — not on every input tick.
  • Every derivedStateOf in the file is inside a remember { … } (or remember(keys) { … }) call.
  • Every derivedStateOf lambda's captured non-state variables appear as remember keys, OR the lambda only reads State objects.
  • Side effects on derived values run via LaunchedEffect { snapshotFlow { … }.collect { } }, not by reading the derived state in the composable body.
  • A grep for derivedStateOf { shows no occurrences where input and output frequencies match (no "$first $last"-shaped uses).

References

Preguntas frecuentes

¿Qué hace la habilidad de IA Choosing Derivedstateof?

Usa esta habilidad para decidir cuándo derivedStateOf de Jetpack Compose es la herramienta adecuada y cuándo solo añade sobrecarga. Explica la regla «la frecuencia de entrada debe superar la frecuencia de salida», el envoltorio obligatorio remember { derivedStateOf { } }, el problema habitual de capturar variables que no son de estado con su valor inicial (y la solución remember(key)) y la alternativa snapshotFlow para efectos secundarios sin espera basados en valores derivados. Úsala cuando el desarrollador mencione derivedStateOf, valores booleanos determinados por la posición de desplaza...

¿Por qué usar Choosing Derivedstateof en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Choosing Derivedstateof 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 Choosing Derivedstateof en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/skydoves/compose-performance-skills/tree/main/recomposition/choosing-derivedstateof. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Choosing Derivedstateof?

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 Choosing Derivedstateof?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Choosing Derivedstateof 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 Choosing Derivedstateof?

Sí. skydoves la ha publicado en GitHub bajo la licencia Apache-2.0. 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 👇