Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
Global scope prop in functional react component

I am using react-native-sound for audio in this component and want to play from a url file that is passed to the component. The problem is that if the var audio is declared inside the functional component then each time the component renders the variable is created again and this plays the sound file as a new instance and we have same sound playing multiple times on top of each other.

import Sound from "react-native-sound"

var audio = new Sound.. //Works if declared here but cant's pass url prop

const SoundPlayer: FC<SoundProps> = ({ url }) => {
    const [playing, setPlaying] = useState<boolean | null>(null)

    var audio = new Sound(url, null, (error) => {
        if (error) {
            console.log("failed to load the sound", error)
            return
        }
    })

If I move the var audio outside / above the functional component as a global variable it works fine but then I can not pass the component prop aka url to it as the variable is out of the function component scope. How can I pass a prop that keeps reference and does not recreate on each render?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Try using useEffect:

const audioRef = useRef(null);
const [duration, setDuration] = useState(0);

useEffect(() => {
   // This will be triggered only once when the component is mounted
   audioRef.current = new Sound(url, null, (error) => {
      if(error) {
         // Here you can implement some retry policy if there was some error loading the sound
         return;
      }

      setDuration(Math.trunc(audioRef.current.getDuration())); 
   });

   return = () => {
     // This will be triggered on component is unmounted
     audioRef.current.release();
   }
}, [audioRef, setDuration]);

P.D.: This code was written on the fly, so further modifications might be needed

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is the correct use case for useRef (https://reactjs.org/docs/hooks-reference.html#useref)

import Sound from "react-native-sound"

const SoundPlayer: FC<SoundProps> = ({ url }) => {
    const audioRef = useRef(null); 
    const [playing, setPlaying] = useState<boolean | null>(null)

  // use useEffect to hook on mounted
   useEffect(() => {
    if(audioRef.current === null) {
      audioRef.current = new Sound(url, null, (error) => {
        if (error) {
            console.log("failed to load the sound", error)
            return
        }
      })
    }
   }, [])


about 4 years ago · Juan Pablo Isaza Denunciar

0

For example

import Sound from "react-native-sound"

var audio;

const SoundPlayer: FC<SoundProps> = ({ url }) => {
    const [playing, setPlaying] = useState<boolean | null>(null)
    
    useEffect(() => {
      audio = new Sound(url, null, (error) => {
          if (error) {
              console.log("failed to load the sound", error)
              return
          }
      })
    }, [url]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda