React
Optional hooks for binding sounds, stable play handlers, and persisted preferences.
The optional @bloxwap/sfx/react entry supports React 18 and 19. React is an optional peer;
importing the core package keeps React out of its bundle.
Bind a subtree
'use client';
import { useRef } from 'react';
import { useBindSounds } from '@bloxwap/sfx/react';
export function Toolbar() {
const ref = useRef<HTMLDivElement>(null);
useBindSounds(ref, { keyboard: true, hoverInterval: 150 });
return <div ref={ref}><button data-sound-press data-sound-release>Save</button></div>;
}The hook binds after mount, rebinds when options change, and cleans up on unmount.
This also works with React Strict Mode. Use bind() directly if you prefer your own effect.
Play from handlers
'use client';
import { useSound } from '@bloxwap/sfx/react';
export function ConfirmButton() {
const confirm = useSound('success', { volume: 0.8 });
return <button onClick={() => confirm({ pan: -0.2 })}>Confirm</button>;
}useSound(name, options?) returns a stable callback while its arguments stay unchanged.
Per-call options override the defaults. Audio unlock still requires a real user gesture.
Persist mute and volume
'use client';
import { SoundProvider, useSoundPreference } from '@bloxwap/sfx/react';
function Preferences() {
const { enabled, volume, setEnabled, setVolume } = useSoundPreference();
return <>
<button onClick={() => setEnabled(!enabled)}>{enabled ? 'Mute' : 'Enable sound'}</button>
<input aria-label="Sound volume" type="range" min={0} max={1} step={0.01}
value={volume} onChange={event => setVolume(Number(event.target.value))} />
</>;
}
export function App() {
return <SoundProvider><Preferences /></SoundProvider>;
}Preferences use the bloxwap:sfx localStorage key. Consumers and browser tabs stay synchronized;
unavailable or invalid storage falls back safely. Volume is clamped to 0–1. The hook can also be
used without a provider.
<SoundProvider enabled volume> can override the stored settings while mounted. Omit a prop to
use its persisted value. Mount one provider near the root: the audio engine is shared across the app.
When the provider unmounts, it restores the saved preference.
Server rendering
Both entry points import safely during SSR. The React entry carries 'use client' for Next.js.
Server output and initial hydration use deterministic defaults; persisted preferences load after
mount. Audio and binding run in effects or user event handlers.
Compose an accepted action
Sound preferences and semantic preview
Web Audio preview. Physical output is not verified on this device. Haptics remain independently owned by your host.
Ready
useSoundHandler('tick', onClick, { disabled, busy, suppressed }) calls your host handler first,
then honors defaultPrevented, state suppression, and nested interactive targets. Attach it to
onClick only: native button keyboard activation already generates a click. It does not
change refs, focus, labels or action timing. Host exceptions retain normal React behavior.
Use committed onChange for switches/selections/sliders, not both pointer and click handlers.
Do not combine automatic bind playback and manual handlers on the same target.
The provider unlocks audio on a trusted pointer/key interaction while enabled and above zero
master volume. It never creates audio during SSR/mount. unlockOnInteraction={false} delegates
unlocking to a host. It removes capture listeners on mute, unmount and prop changes. Browser
API success is not evidence of audible output; OS policy may still suspend or suppress audio.
setCategoryVolume(category, value) persists a 0–1 multiplier for hover, controls, feedback or
money. Existing { enabled, volume } records migrate without replacing saved choices. Bad
category fields are ignored. Missing/corrupt/blocked storage falls back safely; tabs update live.
useSemanticSound(intent, reducedMotion) uses the HIG 0.1.0 mapping from
@bloxwap/sfx/semantic. Reduced mode halves per-play gain without changing stored volume,
sound enablement, animation or haptic preferences. Activation/selection use tick (80 ms),
toggle uses toggle (80 ms), success/error use their matching recipes (400 ms).
Press/release/cancel/disclosure/warning/notification are intentionally silent. Live market
updates remain silent. Essential information belongs in visible state/status, never only sound.
For a HIG app, use FeedbackController from @bloxwap/hig/feedback and
createWebSoundAdapter from @bloxwap/hig/feedback/web-sound instead of adding a second preference/controller store. Pass the SFX engine as the host adapter;
HIG owns independent sound/haptic/motion settings, storage (including native storage), policy,
source/id deduplication, per-source cooldowns, suppression and lifecycle. SFX's hook cadence
is a per-recipe guard, not a substitute for HIG event identity or controlled-value validation.
Use an operation id for delayed success/error; do not infer success from a click.
Shared preference ownership
Imperative setEnabled() and setVolume() calls and React hooks share one store. Mount a SoundProvider in the app root so saved settings are loaded on every route. Provider overrides are temporary; later registered providers take precedence for fields they specify, and removing one restores the remaining owners before falling back to saved settings. Consumers observe the same effective settings.
React Native resolves @bloxwap/sfx/react to native playback hooks without DOM or localStorage access. Use useSound() with onPress; useBindSounds() is a no-op there. Native preferences last for the JS session; persist them through the host app's storage if needed.