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 ?
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.