Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda