Recipe

useSound() — Add small sounds effects to your page

Subtle sounds can bring a page to life

Go Pro

Playgrounds are part of PRO

Frontend.fyi Playgrounds let you take any code example and turn it into a live, editable sandbox — so you can tweak the code, build on it, and learn by doing.

This feature is part of Frontend.fyi PRO, which gives you lifetime access to:

  • Interactive playgrounds (like this one)
  • Full courses (Framer Motion, CSS, and more coming)
  • Copy-paste UI recipes with video walkthroughs
  • Your own public profile to showcase projects and experiments (soon!)

If you're ready to go beyond just watching tutorials and actually build things yourself, PRO is for you.

Subtle sounds can add some life to your page ✨. They make it feel more interactive and engaging.

After using Josh Comeau’s hook useSound for quite a while, I kept stumbling on a few issues with the package that didn’t get fixed. Probably because Josh also moved on from this library.

That is why I decided to write my own basic implementation of the useSound hook. The implementation is based around the standardized Web Audio API. That means we need pretty little code to make a small hook that plays a sound.

Using the hook

To use the hook, you need to pass the URL of the sound you want to play. Optionally you can pass an object with the volume and playback rate settings.

The hook then returns an array with a single function (for now 😉), which you can call to play the sound.

import { useSound } from "./useSound";
const MyComponent = () => {
const [play] = useSound("/path/to/sound.mp3", {
volume: 0.5,
playbackRate: 1.5,
});
return <button onClick={play}>Play sound</button>;
};