React usePrevious Hook: Track Previous State & Props (2026)
Admin User
Author
Summary
React usePrevious Hook: Track Previous State & Props (2026)
The Classic Recipe, and Where It Frays
return ( <div> <button onClick={() => setCount(count + 1)}>+1</button> <button onClick={() => setDark(!dark)}>toggle theme</button> {prevCount !== undefined && prevCount !== count && ( <span>{count > prevCount ? "↑ went up" : "↓ went down"}</span> )} </div> ); }
usePrevious — Previous Value, Not Previous Render
function Counter() { const [count, setCount] = useState(0); const [dark, setDark] = useState(false); const prevCount = usePrevious(count);
return ( <div> <button onClick={() => setCount(count + 1)}>+1</button> <button onClick={() => setDark(!dark)}>toggle theme</button> <p>Now: {count}, before: {prevCount ?? "—"}</p> </div> ); }
if (value !== current) { setPrevious(current); setCurrent(value); }
return previous; }
Wait — setState During Render?
The Gotcha: Unstable Objects
usePrevious vs useLatest
Real Use Cases
SSR Safety
Takeaways
Source
This article discusses content originally published by at Dev.to.