React › Refs, useRef & forwardRef
How would you use a ref to keep track of a component's previous prop value?
IntermediateAnswer
You can store the current prop value inside a ref after each render, using useEffect, so that the next time the component renders, the ref still holds the value from before the update. This lets you compare the current and previous values whenever you need to.
function PriceDisplay({ price }) {
const previousPrice = useRef(price);
useEffect(() => {
previousPrice.current = price;
}, [price]);
const wentUp = price > previousPrice.current;
return <p style={{ color: wentUp ? 'red' : 'green' }}>${price}</p>;
}Real-world example A stock price ticker shows the price in red when it goes up and green when it goes down, by comparing the current price against the previous price stored in a ref from the last render.