React and Vue
Copy a tested hook or composable that attaches, updates and disposes an effect with the component.
These recipes tie an effect’s lifetime to a component. Copy them into your app and change them as needed: they are your code, not a domfx package. Install @domfx/browser as shown in the installation guide first.
Each recipe has two parts: a small hook or composable that owns one effect, and a Fire button that uses it. Both take the same settings:
attach: the effect, such asattachFire.options: creation-only values, such asflameReach. A changed value replaces the effect.controls: writable values, such asintensityandcolor. They update the live effect.refreshOn: values that restyle the host. A change callsrefresh().
Both return lifecycle and reason, so the component can style a fallback.
Save the hook as use-domfx-effect.ts. It works with React 18 and later. Options are compared by value, so inline objects need no useCallback or useMemo, with or without the React Compiler.
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;
}Save the component as FireButton.tsx, with its styles as fire-button.css. Its ‘use client’ line marks it as a client component in Next.js; other setups ignore it.
'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>
);
}/* 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;
}Save the composable as use-domfx-effect.ts. Pass getters, such as () => ({ flameReach }), so prop changes are tracked. Any reactive value read by options replaces the effect when it changes.
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 };
}Save the component as FireButton.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>How the recipes own the effect
Section titled “How the recipes own the effect”- Cleanup is registered before waiting for fonts. Unmounting during setup never creates a late effect.
- React StrictMode mounts twice in development. The first cleanup runs before fonts are ready, so only one effect attaches.
- Unmounting disposes the effect and removes its canvas. Remounting attaches a fresh effect; a disposed effect cannot be reused.
- Control writes render on the next frame without recapturing the target. Creation-only options need a new effect.
- Changes inside the target refresh automatically. Style changes on the host, ancestors or stylesheets need
refresh(). - An unavailable or suspended effect leaves the button working. The button sets
data-effectfromlifecycle, and its CSS shows a static glow instead. Branch onreasonas shown in troubleshooting.
Use another effect
Section titled “Use another effect”Replace attachFire and its options in the component, for example with attachFrost and coatingDepth. The hook and composable work with every attach* function. Each effect reference lists its creation options and writable controls.
Server rendering and GSAP
Section titled “Server rendering and GSAP”Effects are client-only. The recipes attach after mount, so server rendering outputs the plain button, and ‘use client’ keeps the React component out of server components. They were tested with Vite, not with Next.js or Nuxt.
For a timeline, follow the GSAP guide and call its cleanup() from the same teardown: the useEffect cleanup or useGSAP in React, the watcher cleanup or onBeforeUnmount in Vue.
Tested versions
Section titled “Tested versions”Tested with React 18.3.1 and 19.3.1 (StrictMode) and Vue 3.5.45, built with Vite 7.3.7 and TypeScript 5.9.3 against the packed packages, in development and production builds in Chrome.