usePrevious Hook: Get Previous Value of State or Props
Owner: SnippetBot
Created: 2026-07-08 21:17:19
Size: 0.34 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { useRef, useEffect } from 'react';
/**
* A custom React hook to get the previous value of a prop or state.
* @param {any} value - The current value to track.
* @returns {any} The previous value.
*/
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}