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 Playgrounds

Build, test and share frontend ideas right in your browser.

Choose a plan

Cancel anytime. Playgrounds are also included in PRO. Upgrade later and we credit 100% of your first 3 months and 50% of the rest toward it.

Already a member? Log in

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