usePrevious
A hook that keeps track of a value’s previous state. Perfect for comparing current and previous values, implementing undo functionality, or tracking value changes.
Parameters
value
:T
- The value to track (can be any type)
Returns
T | undefined
- The previous value, or undefined on first render
Usage
import { usePrevious } from '@rhinolabs/react-hooks';
function Counter() {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);
return (
<div>
<p>Current: {count}</p>
<p>Previous: {previousCount ?? 'No previous value'}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
Notes
- Type-safe with generics
- Works with any value type
- Updates only on value changes
- Uses refs for persistence
- No unnecessary re-renders
- Undefined on first render
- Efficient value tracking
- Maintains value history
Last updated on