joshwcomeau / use-sound

A React Hook for playing sound effects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SoundManager container

AdrienLemaire opened this issue · comments

Hi @joshwcomeau, and thanks for making this brilliant library.

We would like to have a single container which responsibility is playing sounds, listening to custom events from other components requesting a sound to be played.

This would solve a few issues we're currently facing:

  • wanting a sound to be played when unmounting a component
  • wanting a sound to be played when clicking a link, before redirecting to another page.

Right now, we're adding extra complexity to handle these cases (like adding a state toggled in the onend callback of useSound), but we have a hard time to handle all cases, and got bugs like not being able to navigate to a different page when the sound is disabled.

Do you have suggestions on a clean solution to handle this ? Would you consider supporting it in use-sound?
A similar library already implementing this logic of container & emitter would be react-toastify.

Hey @AdrienLemaire,

Yeah, so I'd say that the requirements of your project exceed what this package was intended for, and I'd suggest creating a more sophisticated tool that can handle it.

The philosophy behind use-sound is that it's a simple way to trigger a sound effect when the user interacts with something. It isn't really meant to orchestrate sounds across the application.

In terms of suggestions, here are my thoughts:

  • You could move the useSound hook into a Context component near the top of your app, and pass the play functions down to children components. Though be sure to check if this has performance implications, use-sound does trigger some re-renders
  • Redux middleware is perfect for these kinds of scenarios. I wrote something a few years ago: https://github.com/joshwcomeau/redux-sounds. Might be worth taking some inspiration from it, even if you don't use redux. You could possibly recreate it using React context.
  • You could use Howler directly, and create your own abstraction. This package is actually quite straightforward, since I'm delegating all of the hard work to Howler. So you could choose a different structure that works well for your application.

Hope that helps!

@joshwcomeau thank you for your detailed answer, this certainly does help!