Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!