Return to site

🪝⏪ USEPREVIOUS HOOK: TRACK THE LAST VALUE IN REACT (WITHOUT EXTRA STATE)

· react,programmmer

Ever needed to compare what you have now vs what you had last render?

That’s exactly what usePrevious gives you: the previous value of a prop/state. ✅

🔸 TL;DR

A tiny hook that lets you access the previous render’s value — ideal for comparisons, transitions, and “only when changed” behaviors. ⏪

Section image

🔸 WHAT IT DOES

usePrevious(value) stores the latest value in a ref, then returns the previous one on the next render.

Perfect when you want “old vs new” without triggering rerenders. 🧠

🔸 THE HOOK

🔸 COMMON USE CASES

▪️ Animations / transitions (detect direction ⬆️⬇️)

▪️ Compare values before running expensive logic ⚡

▪️ Trigger effects only when value actually changed 🔁

▪️ Detect “first time” a value becomes valid (e.g., undefined → value) 🎯

🔸 EXAMPLE: SEARCH INPUT CHANGE DETECTOR

🔸 TAKEAWAYS

▪️ useRef keeps values across renders without causing rerenders ✅

▪️ The first previous value is often undefined (handle it) ⚠️

▪️ Great for “diffing” values instead of adding extra state 🧩

▪️ Use dependency [value] to avoid updating the ref on unrelated renders 🎛️

#react #javascript #webdevelopment #frontend #hooks #reacthooks #devtips #cleancode #performance #uiux