# React y Vue

Copia un hook o composable probado que aplica, actualiza y libera un efecto junto con el componente.

Estas recetas vinculan la vida de un efecto a la de un componente. Cópialas en tu aplicación y adáptalas: son código tuyo, no un paquete de domfx. Primero instala `@domfx/browser` como indica la [guía de instalación](/docs/es/installation/). Los comentarios del código están en inglés.

Cada receta tiene dos partes: un hook o composable pequeño que gestiona un efecto y un botón con Fire que lo usa. Ambos reciben la misma configuración:

* `attach`: el efecto, por ejemplo `attachFire`.
* `options`: valores de creación, como `flameReach`. Un valor nuevo sustituye el efecto.
* `controls`: valores modificables, como `intensity` y `color`. Actualizan el efecto activo.
* `refreshOn`: valores que cambian el estilo del contenedor. Un cambio llama a `refresh()`.

Ambos devuelven `lifecycle` y `reason`, así el componente puede mostrar un estilo alternativo.

## React

[Sección titulada «React»](#react)

Guarda el hook como `use-domfx-effect.ts`. Funciona con React 18 y posterior. Las opciones se comparan por valor, así que los objetos en línea no necesitan `useCallback` ni `useMemo`, con o sin React Compiler.

```ts
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';

import type { EffectHandle } from '@domfx/browser';

export interface DomfxEffectConfig<
  O extends { readonly host: HTMLElement },
  E extends EffectHandle,
> {
  /** Positioned element that holds the effect canvas. */
  host: RefObject<HTMLElement | null>;
  /** Element the effect captures and decorates. */
  target: RefObject<HTMLElement | null>;
  /** An attach function, such as attachFire. */
  attach: (target: HTMLElement, options: O) => E;
  /** Creation-only plain values. A changed value replaces the effect. */
  options?: NoInfer<Omit<O, 'host'>>;
  /** Writable values, such as intensity, applied to the live effect. */
  controls?: NoInfer<Partial<E>>;
  /** Values that restyle the host or its ancestors. A change calls refresh(). */
  refreshOn?: readonly unknown[];
}

export interface DomfxEffectState<E extends EffectHandle> {
  effect: E | undefined;
  /** Undefined until the effect is ready. */
  lifecycle: E['lifecycle'] | undefined;
  /** Why the effect is unavailable or suspended. */
  reason: E['reason'];
}

const idle = { effect: undefined, lifecycle: undefined, reason: undefined };

/** Owns one effect while the component is mounted. Works with React 18 and later. */
export function useDomfxEffect<O extends { readonly host: HTMLElement }, E extends EffectHandle>({
  host,
  target,
  attach,
  options,
  controls = {},
  refreshOn = [],
}: DomfxEffectConfig<O, E>): DomfxEffectState<E> {
  const [state, setState] = useState<DomfxEffectState<E>>(idle);
  // React treats values returned from hooks as immutable, so writes go through a ref.
  const live = useRef<{ effect: E; written: Partial<E>; refreshKey: string }>(undefined);
  // Creation options and refresh values are plain data, so a string detects changes.
  const optionsKey = JSON.stringify(options ?? {});
  const refreshKey = JSON.stringify(refreshOn);

  // The latest config, read by effects without making it a dependency. Effects run
  // in order, so this updates first. On React 19.2+, useEffectEvent can replace it.
  const latest = useRef({ attach, options, controls, refreshKey });
  useEffect(() => {
    latest.current = { attach, options, controls, refreshKey };
  });

  const report = useCallback((effect: E) => {
    if (live.current?.effect === effect) {
      setState({ effect, lifecycle: effect.lifecycle, reason: effect.reason });
    }
  }, []);

  useEffect(() => {
    const hostElement = host.current;
    const targetElement = target.current;
    if (!hostElement || !targetElement) {
      return;
    }
    let disposed = false;
    let current: E | undefined;

    void document.fonts.ready.then(async () => {
      if (disposed) {
        return;
      }
      const config = latest.current;
      // Omit<O, 'host'> plus host is O, which TypeScript cannot prove for a generic O.
      current = config.attach(targetElement, { ...config.options, host: hostElement } as O);
      Object.assign(current, config.controls);
      live.current = {
        effect: current,
        written: { ...config.controls },
        refreshKey: config.refreshKey,
      };
      setState({ ...idle, effect: current });
      await current.ready;
      report(current);
    });

    // Runs on unmount, before re-creating, and between StrictMode's double mount.
    return () => {
      disposed = true;
      current?.dispose();
      live.current = undefined;
      setState(idle);
    };
  }, [host, target, optionsKey, report]);

  // Runs after every render and writes only changed controls; each write draws a frame.
  useEffect(() => {
    const entry = live.current;
    if (!entry) {
      return;
    }
    for (const key of Object.keys(controls) as (keyof E)[]) {
      if (!Object.is(entry.written[key], controls[key])) {
        Object.assign(entry.effect, { [key]: controls[key] });
        entry.written[key] = controls[key];
      }
    }
  });

  // Target changes refresh automatically; host and ancestor styles do not.
  useEffect(() => {
    const entry = live.current;
    if (!entry || entry.refreshKey === refreshKey) {
      return;
    }
    entry.refreshKey = refreshKey;
    // Rejects after disposal or a failed capture; lifecycle and reason report it.
    void entry.effect
      .refresh()
      .catch(() => {})
      .then(() => report(entry.effect));
  }, [refreshKey, report]);

  return state;
}
```

Guarda el componente como `FireButton.tsx` y sus estilos como `fire-button.css`. La línea `‘use client’` lo marca como componente de cliente en Next.js; otros entornos la ignoran.

```tsx
'use client';

import { useRef, type ReactNode } from 'react';

import { attachFire } from '@domfx/browser';

import './fire-button.css';
import { useDomfxEffect } from './use-domfx-effect';

interface FireButtonProps {
  children: ReactNode;
  onClick?: () => void;
  /** Creation-only: a change replaces the effect. */
  flameReach?: number;
  /** Writable: applied to the live effect. */
  intensity?: number;
  color?: string;
  /** Styles the host, which the effect does not observe. */
  tone?: 'calm' | 'alert';
}

export function FireButton({
  children,
  onClick,
  flameReach,
  intensity = 0.8,
  color,
  tone = 'calm',
}: FireButtonProps) {
  const host = useRef<HTMLDivElement>(null);
  const target = useRef<HTMLButtonElement>(null);
  const { lifecycle } = useDomfxEffect({
    host,
    target,
    attach: attachFire,
    options: { clock: 'auto', flameReach },
    controls: { intensity, color },
    refreshOn: [tone],
  });

  return (
    <div ref={host} className="fire-host" data-tone={tone} data-effect={lifecycle}>
      <button ref={target} className="fire-target" type="button" onClick={onClick}>
        {children}
      </button>
    </div>
  );
}
```

```css
/* The host is positioned and leaves room above the button for the flames. */
.fire-host {
  position: relative;
  display: inline-block;
  padding: 72px 32px 16px;
}

.fire-target {
  padding: 12px 20px;
  border: 0;
  border-radius: 8px;
  color: #fff;
  background: #1f2937;
  font:
    600 1rem/1 system-ui,
    sans-serif;
}

.fire-host[data-tone='alert'] .fire-target {
  background: #b91c1c;
}

/* Without a live effect, a static glow keeps the button's look. */
.fire-host:is([data-effect='unavailable'], [data-effect='suspended']) .fire-target {
  box-shadow: 0 -4px 24px #f97316;
}
```

## Vue

[Sección titulada «Vue»](#vue)

Guarda el composable como `use-domfx-effect.ts`. Pasa getters, como `() => ({ flameReach })`, para que se sigan los cambios de las props. Cualquier valor reactivo que lea `options` sustituye el efecto cuando cambia.

```ts
import {
  shallowRef,
  toValue,
  watch,
  watchEffect,
  type MaybeRefOrGetter,
  type ShallowRef,
} from 'vue';

import type { EffectHandle } from '@domfx/browser';

export interface DomfxEffectConfig<
  O extends { readonly host: HTMLElement },
  E extends EffectHandle,
  P extends Omit<O, 'host'>,
> {
  /** Positioned element that holds the effect canvas. */
  host: MaybeRefOrGetter<HTMLElement | null>;
  /** Element the effect captures and decorates. */
  target: MaybeRefOrGetter<HTMLElement | null>;
  /** An attach function, such as attachFire. */
  attach: (target: HTMLElement, options: O) => E;
  /** Creation-only values. A change to a value read here replaces the effect.
   * The Record rejects keys the attach function does not accept. */
  options?: () => P & Record<Exclude<keyof P, keyof O>, never>;
  /** Writable values, such as intensity, applied to the live effect. */
  controls?: () => NoInfer<Partial<E>>;
  /** Values that restyle the host or its ancestors. A change calls refresh(). */
  refreshOn?: MaybeRefOrGetter<unknown>;
}

export interface DomfxEffectState<E extends EffectHandle> {
  effect: Readonly<ShallowRef<E | undefined>>;
  /** Undefined until the effect is ready. */
  lifecycle: Readonly<ShallowRef<E['lifecycle'] | undefined>>;
  /** Why the effect is unavailable or suspended. */
  reason: Readonly<ShallowRef<E['reason']>>;
}

/** Owns one effect while the component is mounted. */
// `const P` keeps literal options such as clock: 'auto' from widening to string.
export function useDomfxEffect<
  O extends { readonly host: HTMLElement },
  E extends EffectHandle,
  const P extends Omit<O, 'host'>,
>({
  host,
  target,
  attach,
  options,
  controls,
  refreshOn,
}: DomfxEffectConfig<O, E, P>): DomfxEffectState<E> {
  const effect = shallowRef<E>();
  const lifecycle = shallowRef<E['lifecycle']>();
  const reason = shallowRef<E['reason']>();

  const report = (current: E) => {
    if (effect.value === current) {
      lifecycle.value = current.lifecycle;
      reason.value = current.reason;
    }
  };

  watchEffect(
    (onCleanup) => {
      const hostElement = toValue(host);
      const targetElement = toValue(target);
      const creation = options?.();
      if (!hostElement || !targetElement) {
        return;
      }
      let disposed = false;
      let current: E | undefined;

      // Runs on unmount and before re-creating, including while fonts are pending.
      onCleanup(() => {
        disposed = true;
        current?.dispose();
        effect.value = undefined;
        lifecycle.value = undefined;
        reason.value = undefined;
      });

      void document.fonts.ready.then(async () => {
        if (disposed) {
          return;
        }
        // Omit<O, 'host'> plus host is O, which TypeScript cannot prove for a generic O.
        current = attach(targetElement, { ...creation, host: hostElement } as O);
        Object.assign(current, controls?.());
        effect.value = current;
        await current.ready;
        report(current);
      });
    },
    { flush: 'post' },
  );

  // Reruns when a control or the effect changes; each write draws a frame.
  watchEffect(() => {
    if (effect.value) {
      Object.assign(effect.value, controls?.());
    }
  });

  // Target changes refresh automatically; host and ancestor styles do not.
  watch(
    () => toValue(refreshOn),
    () => {
      const current = effect.value;
      if (!current) {
        return;
      }
      // Rejects after disposal or a failed capture; lifecycle and reason report it.
      void current
        .refresh()
        .catch(() => {})
        .then(() => report(current));
    },
    { flush: 'post' },
  );

  return { effect, lifecycle, reason };
}
```

Guarda el componente como `FireButton.vue`.

```vue
<script setup lang="ts">
import { useTemplateRef } from 'vue';

import { attachFire } from '@domfx/browser';

import { useDomfxEffect } from './use-domfx-effect';

const {
  flameReach,
  intensity = 0.8,
  color,
  tone = 'calm',
} = defineProps<{
  /** Creation-only: a change replaces the effect. */
  flameReach?: number;
  /** Writable: applied to the live effect. */
  intensity?: number;
  color?: string;
  /** Styles the host, which the effect does not observe. */
  tone?: 'calm' | 'alert';
}>();
const emit = defineEmits<{ click: [] }>();

const host = useTemplateRef<HTMLDivElement>('host');
const target = useTemplateRef<HTMLButtonElement>('target');

const { lifecycle } = useDomfxEffect({
  host,
  target,
  attach: attachFire,
  options: () => ({ clock: 'auto', flameReach }),
  controls: () => ({ intensity, color }),
  refreshOn: () => tone,
});
</script>

<template>
  <div ref="host" class="fire-host" :data-tone="tone" :data-effect="lifecycle">
    <button ref="target" class="fire-target" type="button" @click="emit('click')">
      <slot />
    </button>
  </div>
</template>

<style>
/* The host is positioned and leaves room above the button for the flames. */
.fire-host {
  position: relative;
  display: inline-block;
  padding: 72px 32px 16px;
}

.fire-target {
  padding: 12px 20px;
  border: 0;
  border-radius: 8px;
  color: #fff;
  background: #1f2937;
  font: 600 1rem/1 system-ui, sans-serif;
}

.fire-host[data-tone='alert'] .fire-target {
  background: #b91c1c;
}

/* Without a live effect, a static glow keeps the button's look. */
.fire-host:is([data-effect='unavailable'], [data-effect='suspended']) .fire-target {
  box-shadow: 0 -4px 24px #f97316;
}
</style>
```

## Cómo gestionan el efecto

[Sección titulada «Cómo gestionan el efecto»](#cómo-gestionan-el-efecto)

* La limpieza se registra antes de esperar las fuentes. Desmontar durante la preparación nunca crea un efecto tardío.
* StrictMode de React monta dos veces en desarrollo. La primera limpieza ocurre antes de que las fuentes estén listas, así que solo se aplica un efecto.
* Desmontar libera el efecto y retira su canvas. Volver a montar aplica un efecto nuevo; un efecto liberado no se puede reutilizar.
* Los controles se muestran en el siguiente fotograma sin volver a capturar el objetivo. Las opciones de creación necesitan un efecto nuevo.
* Los cambios dentro del objetivo actualizan la captura automáticamente. Los cambios de estilo en el contenedor, los ancestros o las hojas de estilo necesitan `refresh()`.
* Si el efecto no está disponible o está suspendido, el botón sigue funcionando. El botón asigna `data-effect` a partir de `lifecycle` y su CSS muestra un brillo estático. Consulta cómo usar `reason` en [solución de problemas](/docs/es/troubleshooting/).

## Usa otro efecto

[Sección titulada «Usa otro efecto»](#usa-otro-efecto)

Sustituye `attachFire` y sus opciones en el componente, por ejemplo por `attachFrost` y `coatingDepth`. El hook y el composable funcionan con todas las funciones `attach*`. Cada [referencia de efecto](/docs/es/api/effects/) enumera sus opciones de creación y sus controles modificables.

## Renderizado en servidor y GSAP

[Sección titulada «Renderizado en servidor y GSAP»](#renderizado-en-servidor-y-gsap)

Los efectos solo funcionan en el cliente. Las recetas aplican el efecto después del montaje, así que el renderizado en servidor genera el botón sin efecto, y `‘use client’` mantiene el componente de React fuera de los componentes de servidor. Se probaron con Vite, no con Next.js ni Nuxt.

Para una línea de tiempo, sigue la [guía de GSAP](/docs/es/gsap/) y llama a su `cleanup()` desde la misma limpieza: la de `useEffect` o `useGSAP` en React, y la del watcher u `onBeforeUnmount` en Vue.

## Versiones probadas

[Sección titulada «Versiones probadas»](#versiones-probadas)

Probado con React 18.3.1 y 19.3.1 (StrictMode) y Vue 3.5.45, compilado con Vite 7.3.7 y TypeScript 5.9.3 a partir de los paquetes empaquetados, en compilaciones de desarrollo y producción en Chrome.
