3 ms·
Could some one clarify for me why the consts for the useSound() are declared inside an array? const [play] = useSound()
by vcoelho 7y ago
Could some one clarify for me why the consts for the useSound() are declared inside an array?
const [play] = useSound()
- hazz99 7y agoIt'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.
- gherkinnn 7y agouseSound 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().
- joshwcomeau 7y agoOther 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.