Skip to content

useSound

Named sound effects with mute toggle.

A React hook that plays named sound effects from a { name: src } library. Caches Audio elements, resets playback per trigger, and persists mute state (via use-local-storage).

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-sound

Usage

import { useSound } from "@/hooks/use-sound";
 
const sounds = {
  pop: "/sounds/pop.mp3",
  success: "/sounds/success.mp3",
} as const;
 
function Toolbar() {
  const { play, muted, setMuted } = useSound(sounds);
 
  return (
    <>
      <button onClick={() => play("pop")}>Pop</button>
      <button onClick={() => play("success", { volume: 0.5 })}>Quiet success</button>
      <button onClick={() => setMuted(!muted)}>{muted ? "Unmute" : "Mute"}</button>
    </>
  );
}

Playback failures (autoplay policy, missing file) are swallowed. volume is clamped to 0–1.

API

function useSound<TLibrary extends Record<string, string>>(
  library: TLibrary,
): {
  play: (name: keyof TLibrary & string, opts?: { volume?: number }) => void;
  muted: boolean;
  setMuted: Dispatch<SetStateAction<boolean>>;
};

Parameters

Return value