@ryvora/react-use-previous
v2.0.0
Published
⏪🕰️ Get the previous value of a prop or state in React. Time travel for your components!
Maintainers
Readme
use-previous ⏪🕰️
Hello Time Traveler! ⏳
The use-previous hook is a handy little utility that lets you get the value of a prop or state from the previous render.
It's like having a little rearview mirror 🚗🔍 for your component's data, allowing you to see what it just was.
Why would you need this?
- Comparing current props/state to previous props/state to trigger effects or derive new state.
- Running cleanup logic in
useEffectbased on a previous value. - Displaying changes or deltas.
How it Works (Typically):
It uses a useRef to store the value after each render, and returns the ref's current value (which is the value from the previous render cycle) before updating the ref with the new current value.
Basic Usage
import { usePrevious } from '@ryvora/react-use-previous'; // Hook name might vary
import React, { useState, useEffect } from 'react';
function CountTracker() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
useEffect(() => {
if (prevCount !== undefined && count > prevCount) {
console.log(`Count increased from ${prevCount} to ${count}!`);
} else if (prevCount !== undefined && count < prevCount) {
console.log(`Count decreased from ${prevCount} to ${count}!`);
}
}, [count, prevCount]);
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCount === undefined ? 'N/A' : prevCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}Look back (but not in anger 😉) and make your components even smarter! ✨🧠
