Recipe

useSound() — Add small sounds effects to your page

Subtle sounds can bring a page to life

User avatar

Jeroen Reumkens PRO

Playing a sound with React Hooks

Unlock Playground Access

Playgrounds let you build, test, and share frontend ideas instantly — right in your browser. Access is included in PRO. Just want Playgrounds? Pick a plan below.

Maker

€5,- / month

Unlimited Playgrounds access to build, experiment, and share without limits.

Join for €5 per month

Champion

€10,- / month

All the benefits of Maker, plus you help Frontend.fyi grow and get a Champion badge on your profile.

Join for €10 per month

Cancel anytime — no commitment.
Upgrade to PRO anytime and get a partial refund.We'll credit 100% of your first 3 months and 50% of the rest toward the PRO lifetime price.

Already a member? Login

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>;
};