Skip to content

Instantly share code, notes, and snippets.

@munshkr
Last active May 16, 2024 04:56
Show Gist options
  • Save munshkr/d4ff7b2ba764e6b5328bd2936c91ec32 to your computer and use it in GitHub Desktop.
Save munshkr/d4ff7b2ba764e6b5328bd2936c91ec32 to your computer and use it in GitHub Desktop.
Hydra Synth hook for React

Hydra Synth hook for React

For Vite, you will have to define global.window, and this has to be defined before importing Hydra. You can do this by adding a define in the Vite config file:

import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  define: {
    global: {
      window: {}
    },
  }
})
import { useHydra } from './useHydra'
import { useEffect } from 'react'
function App() {
const [canvasRef, hydraLoaded] = useHydra()
useEffect(() => {
if (!hydraLoaded) return;
// when it's loaded, run this script:
noise().out();
}, [hydraLoaded])
return (
<canvas style={{ width: '100vw', height: '100vh' }} ref={canvasRef} />
)
}
export default App
import { useEffect, useRef, useState } from "react";
import Hydra from "hydra-synth";
export function useHydra() {
const canvasRef = useRef(null)
const [loaded, setLoaded] = useState(false)
useEffect(() => {
const hydra = new Hydra({
canvas: canvasRef.current,
detectAudio: false,
});
window.hydra = hydra;
setLoaded(true);
return () => {
hydra.hush();
};
}, [canvasRef]);
return [canvasRef, loaded];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment