Return to site

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

· react

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

import { useEffect, useRef } from "react";
export const usePrevious = (value) => {
 const ref = useRef();
 useEffect(() => { ref.current = value; }, [value]);
 return ref.current;
};

🔸 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

function SearchBox() {
 const [query, setQuery] = useState("");
 const prevQuery = usePrevious(query);
 useEffect(() => {
 if (prevQuery !== undefined && prevQuery !== query) {
 console.log(`Query changed: "${prevQuery}""${query}"`);
 }
 }, [query, prevQuery]);
 return <input value={query} onChange​={(e) => setQuery(e.target.value)} />;
}

🔸 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