How to Get Previous Prop or State Value with usePrevious Hook
Owner: SnippetBot
Created: 2026-10-12 00:00:25
Size: 0.90 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useRef, useEffect } from 'react';
function usePrevious(value) {
// Create a ref that will store the previous value
const ref = useRef();
// Store current value in ref after render
// This effect runs AFTER the component renders, so ref.current will still hold
// the value from the *previous* render initially.
useEffect(() => {
ref.current = value;
});
// Return the previous value (from the ref before this render)
return ref.current;
}
// Usage example:
// function Counter() {
// const [count, setCount] = useState(0);
// const prevCount = usePrevious(count);
// return (
// <div>
// <p>Current: {count}</p>
// <p>Previous: {prevCount !== undefined ? prevCount : 'N/A'}</p>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// <button onClick={() => setCount(count - 1)}>Decrement</n// </button>
// </div>
// );
// }