Hacker News new | ask | show | jobs
by vcoelho 2271 days ago
Could some one clarify for me why the consts for the useSound() are declared inside an array?

const [play] = useSound()

3 comments

Other commenters beat me to it, but yeah, it's an ergonomics thing. If you have multiple sounds, you can do:

const [playBell, bellOptions] = useSound();

const [playBoom, boomOptions] = useSound();

It follows the convention of other React hooks, like useState.

It's the pattern/convention that the React team used for the built-in hooks.

const [ myState, setMyState ] = useState(initalValue);

In this case, the "play" is a function to play the sound, and the next array argument is an object with more useful parameters.

const [ play, args ] = useSound()

I assume it's a workaround/replacement for returning a tuple in vanilla JavaScript.

useSound returns an array (used like a tuple here).

The syntax you see here is Array Destructuring. This way you access the 0th element directly.

Equivalent of:

const hook = useSound() const play = hook[0]

If you want to just take the 2nd item, you can destructure like this: const [, pause] = useSound().