Back to results for “Refs”
React › Refs, useRef & forwardRef

How would you use a ref to keep track of a component's previous prop value?

Intermediate

Answer

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.

Common follow-ups: Why can you not simply compare the current prop against a regular variable declared inside the component?;How would you achieve similar previous value tracking using a custom hook?