React hook to get previous value of state or props
1import { useRef, useEffect } from 'react';
2
3function usePrevious<T>(value: T): T | undefined {
4 const ref = useRef<T>();
5
6 useEffect(() => {
7 ref.current = value;
8 }, [value]);
9
10 return ref.current;
11}
12
13// Usage example
14function Counter() {
15 const [count, setCount] = useState(0);
16 const prevCount = usePrevious(count);
17
18 return (
19 <div>
20 <p>Current: {count}</p>
21 <p>Previous: {prevCount}</p>
22 <button onClick={() => setCount(count + 1)}>
23 Increment
24 </button>
25 </div>
26 );
27}Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.