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

174
Vistas
useRef is sometimes undefined even tho value exists

I'm trying to keep a previous value that is constantly updated through my store using the useRef hook as below, however, the ref value is sometimes undefined even tho I am only setting it when the value exists.

const price = useSelector(getPrice(props.index));
let prevPriceRef = useRef();

useEffect(() => {
        if(price) {
            prevPriceRef.current = price;
        }
    }, [ price ])

console.log(prevPriceRef.current) sometimes returns undefined, who is it possible ?

enter image description here

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

0

Create a separate hook to handle/record previous value

function usePrevious(value) {

  const ref = useRef();
  
  useEffect(() => {
    ref.current = value;
  }, [value]); 

  return ref.current;
}

Use it by calling

const prevPrice = usePrevious(price);

One thing to note, you are checking for if (price) {} which will not execute if your price is 0 => Zero and will return undefined as you will not be setting the current value to the ref.

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