platform-codebase/@packages/@hooks/react-hooks/src/use-previous.ts

43 lines
1,019 B
TypeScript
Raw Normal View History

import { useRef, useEffect } from 'react';
/**
* Hook for tracking the previous value of a variable
*
* Useful for comparing current and previous values in effects
* or for animation transitions.
*
* @param value - Current value to track
* @returns Previous value (undefined on first render)
*
* @example
* ```typescript
* function Counter() {
* const [count, setCount] = useState(0);
* const previousCount = usePrevious(count);
*
* useEffect(() => {
* if (previousCount !== undefined && count > previousCount) {
* console.log('Count increased!');
* }
* }, [count, previousCount]);
*
* return (
* <div>
* <p>Current: {count}</p>
* <p>Previous: {previousCount ?? 'N/A'}</p>
* <button onClick={() => setCount(count + 1)}>Increment</button>
* </div>
* );
* }
* ```
*/
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}