Skip to content

React Integration ​

Play the React example here or use its hooks in your own components. The first click can load a sample and play it. The same hooks handle oscillators, polyphonic synths and the transport clock.

Install ​

The example runs the upcoming 0.2.0 packages from this repository. Once the release is on npm, install the core and the React binding together in your React app.

bash
npm install ez-web-audio @ez-web-audio/react

The Hook Shape ​

Every factory hook returns five fields:

typescript
interface UseFactoryReturn<T, Args extends unknown[]> {
  instance: T | null
  loading: boolean
  error: Error | null
  load: (...args: Args) => Promise<T>
  reset: () => void
}

Nothing happens until you call load(...). instance stays null, loading stays false, and — critically for SSR — no AudioContext is touched until then.

This shape is identical, field for field, to @ez-web-audio/vue's composables. If you already know one package, you know the other's data model; only the reactivity mechanism around it differs (see the BeatTrack section below).

The bindings include 15 factory hooks:

useAnalyzer, useBeatTrack, useFont, useGrainPlayer, useLayeredSound, useLFO, useOscillator, usePolySynth, useSampler, useSequence, useSound, useSprite, useTrack, useTransport, useWhiteNoise.

Plus two lifecycle hooks that aren't factories:

  • useCleanup — registers instances for automatic teardown on unmount.
  • useAudioContext — exposes the shared AudioContext's ready state and an explicit init().

Cleanup and First-Interaction Init ​

A factory hook keeps the instrument in instance and re-renders when load() resolves. Register it with useCleanup() to stop and dispose it on unmount. Use reset() when changing the input to an already loaded hook. A load that finishes after a reset discards its result and rejects with AbortError.

If you need to warm up the shared context ahead of a factory hook — for example, priming iOS's audio unlock before the user reaches the control that calls load() — call useAudioContext().init() from an event handler:

tsx
import { useAudioContext } from '@ez-web-audio/react'

function UnlockButton() {
  const { ready, init } = useAudioContext()

  return (
    <button type="button" onClick={() => init()} disabled={ready}>
      {ready ? 'Audio ready' : 'Enable audio'}
    </button>
  )
}

init() is idempotent and safe to call multiple times or from multiple components — it de-dupes concurrent calls and resolves immediately once the context is ready.

Full Examples ​

The components below come from the standalone app embedded on this page. They use a local sample when built with the docs. Complete source and imports

One-shot playback with useSound ​

CLICK_URL points to a short audio file. The first click requests it, and later clicks replay the decoded sample.

tsx
function ClickSound(): ReactElement {
  const { instance, loading, error, load } = useSound()
  const cleanup = useCleanup()
  const [playbackError, setPlaybackError] = useState('')

  async function handleClick(): Promise<void> {
    try {
      setPlaybackError('')
      const sound = instance ?? cleanup.register(await load(CLICK_URL))
      await sound.play()
    }
    catch (err) {
      setPlaybackError(err instanceof Error ? err.message : 'Could not play the sample.')
    }
  }

  return (
    <section>
      <h2>useSound — one-shot playback</h2>
      <button type="button" onClick={handleClick} disabled={loading}>
        {loading ? 'Loading…' : 'Play Click'}
      </button>
      {(error || playbackError) && <p role="alert">{error?.message ?? playbackError}</p>}
    </section>
  )
}

Play and stop with useOscillator ​

The toggle stores its button state in React. The oscillator plays A4 on the first press and releases the note on the next.

tsx
function OscillatorToggle(): ReactElement {
  const { instance, loading, error, load } = useOscillator()
  const cleanup = useCleanup()
  const [playing, setPlaying] = useState(false)

  const [playbackError, setPlaybackError] = useState('')

  async function handleClick(): Promise<void> {
    try {
      setPlaybackError('')
      const osc = instance ?? cleanup.register(await load({
        frequency: 440,
        type: 'sawtooth',
        envelope: { attack: 0.01, decay: 0.2, sustain: 0.5, release: 0.3 },
      }))

      if (playing)
        await osc.stop()
      else
        await osc.play()
      setPlaying(!playing)
    }
    catch (err) {
      setPlaybackError(err instanceof Error ? err.message : 'Could not play the oscillator.')
    }
  }

  return (
    <section>
      <h2>useOscillator — play / stop</h2>
      <button type="button" onClick={handleClick} disabled={loading}>
        {loading ? 'Loading…' : playing ? 'Stop' : 'Play A4 Sawtooth'}
      </button>
      {(error || playbackError) && <p role="alert">{error?.message ?? playbackError}</p>}
    </section>
  )
}

Mini keyboard — usePolySynth and VoiceHandle ​

synth.play(...) returns a VoiceHandle for each note. Record the pointer press before loading the synth. If the player releases the key while audio is loading, discard that press so the note stays silent. Once a note starts, releasing the key calls stop() on its voice.

tsx
function MiniKeyboard(): ReactElement {
  const { instance, error, load } = usePolySynth()
  const { register } = useCleanup()
  const presses = useRef(new Map<number, { voice?: VoiceHandle }>())
  useEffect(() => {
    const held = presses.current
    return () => held.clear()
  }, [])

  async function noteOn(pointerId: number, frequency: number): Promise<void> {
    const held = presses.current
    if (held.has(pointerId))
      return
    const press: { voice?: VoiceHandle } = {}
    held.set(pointerId, press)

    let synth: PolySynth
    try {
      synth = instance ?? register(await load({
        type: 'triangle',
        envelope: { attack: 0.01, decay: 0.2, sustain: 0.5, release: 0.3 },
      }))
    }
    catch {
      // The hook exposes the load failure in error for the alert below.
      if (held.get(pointerId) === press)
        held.delete(pointerId)
      return
    }

    // A later press can reuse the same pointer ID.
    if (held.get(pointerId) === press)
      press.voice = synth.play({ frequency })
  }

  function noteOff(pointerId: number): void {
    const press = presses.current.get(pointerId)
    presses.current.delete(pointerId)
    void press?.voice?.stop()
  }

  return (
    <section>
      <h2>usePolySynth — mini keyboard</h2>
      <div className="keyboard">
        {KEYS.map(({ note, frequency }) => (
          <button
            key={note}
            type="button"
            onPointerDown={event => noteOn(event.pointerId, frequency)}
            onPointerUp={event => noteOff(event.pointerId)}
            onPointerLeave={event => noteOff(event.pointerId)}
            onPointerCancel={event => noteOff(event.pointerId)}
          >
            {note}
          </button>
        ))}
      </div>
      {error && <p className="error">{error.message}</p>}
    </section>
  )
}

SSR and Next.js ​

Importing ez-web-audio and @ez-web-audio/react is safe at module scope in an SSR environment — the shared AudioContext is created lazily inside getOrCreateAudioContext(), which only runs when a factory hook's load() (or useAudioContext().init()) actually executes from an event handler. No top-level code touches window or constructs an AudioContext.

Even so, in a Next.js App Router project:

  • Add 'use client' to the top of any component file that calls these hooks — they use useState/useEffect/useRef internally and cannot run in a Server Component.
  • Don't call load() in a bare useEffect on mount — that reintroduces the "AudioContext created without a user gesture" problem the hooks are designed to avoid. Gate audio creation behind a real interaction (click, keypress), exactly as the examples above do.
  • useAudioContext()'s own init() dynamically import()s ez-web-audio rather than importing it eagerly — a defensive pattern worth mirroring if you lazy-load other browser-only modules alongside it. Combine with next/dynamic ({ ssr: false }) for a component if it does non-audio browser-only work too (canvas, ResizeObserver, etc.) at render time — the hooks themselves don't require it.

BeatTrack: Where React and Vue Diverge ​

useBeatTrack returns the same { instance, loading, error, load, reset } shape as every other hook — instance is a real BeatTrack with a beats array. This is the one spot where the parity with @ez-web-audio/vue breaks, because the two frameworks have fundamentally different reactivity models:

@ez-web-audio/vue@ez-web-audio/react
beats arrayWrapped via wrapWith: beat => reactive(beat)Plain Beat instances, unwrapped
Mutating beat.active/currentTimeIsPlayingTriggers a re-render automaticallyInvisible to React — no proxy, no signal
How the UI reflects playbackTemplate binds directly to beat.currentTimeIsPlayingPoll on requestAnimationFrame, or listen for the beat event
Setup costOne option (wrapWith)A small polling loop or event subscription

Vue's reactive() is a proxy that Vue's renderer already watches; React has no built-in equivalent that works on a plain class instance. BeatTrack.beats[i].active = true will change the object, but nothing tells React to re-render — you have to ask for the update yourself, one of two ways.

Pattern A: requestAnimationFrame polling ​

Read beatTrack.beats every frame and copy the fields you care about into state:

tsx
function useBeatTrackPlayhead(beatTrack: BeatTrack | null) {
  const [currentBeat, setCurrentBeat] = useState<number | null>(null)
  const rafRef = useRef<number>(0)

  useEffect(() => {
    if (!beatTrack)
      return

    function tick() {
      const playing = beatTrack!.beats.findIndex(b => b.currentTimeIsPlaying)
      setCurrentBeat(playing === -1 ? null : playing)
      rafRef.current = requestAnimationFrame(tick)
    }

    rafRef.current = requestAnimationFrame(tick)
    return () => cancelAnimationFrame(rafRef.current)
  }, [beatTrack])

  return currentBeat
}

This is the same rAF-over-audioContext.currentTime mechanism the library uses internally for timing — see Vanilla TS Events for why it doesn't drift.

Pattern B: the beat event ​

BeatTrack emits a beat event at play time via its internal TypedEventEmitter, carrying { time, beatIndex, active, source } in event.detail. Subscribe in a useEffect and mirror it into state:

tsx
function useBeatTrackPlayhead(beatTrack: BeatTrack | null) {
  const [currentBeat, setCurrentBeat] = useState<number | null>(null)

  useEffect(() => {
    if (!beatTrack)
      return

    function onBeat(e: CustomEvent<{ beatIndex: number, active: boolean }>) {
      setCurrentBeat(e.detail.beatIndex)
    }

    beatTrack.on('beat', onBeat)
    return () => {
      beatTrack.off('beat', onBeat)
    }
  }, [beatTrack])

  return currentBeat
}

Either pattern works — polling is simpler when you also need continuous values (e.g. driving a CSS transform every frame); the event is cheaper when you only care about discrete beat boundaries. Both ride the same audioContextAwareTimeout scheduling as the Vue reactive() path, so timing precision is identical across all three approaches — only the plumbing that gets state into your UI differs.

Play the React example ​

View the React example source on GitHub

See Also ​