usePrevious
The value from the previous render.
Returns whatever the value was last render, or undefined on the first — for
reacting to a transition rather than a state.
Usage
import { usePrevious } from 'panelui-native';
function Sheet({ isOpen }: { isOpen: boolean }) {
const wasOpen = usePrevious(isOpen);
useEffect(() => {
// Fires on the open, not on every render while open.
if (isOpen && !wasOpen) track('sheet_opened');
}, [isOpen, wasOpen]);
}Examples
Animating in the direction of travel
The previous value is what tells you which way a number moved.
const previous = usePrevious(score);
const rising = previous !== undefined && score > previous;
<Text className={rising ? 'text-green-600' : 'text-red-600'}>
{score}
</Text>;Reacting to a value arriving
Runs once, when the data first appears — not on every render afterwards.
const previousUser = usePrevious(user);
useEffect(() => {
if (user && !previousUser) {
toast({ variant: 'success', title: `Welcome back, ${user.name}` });
}
}, [user, previousUser]);Detecting a specific transition
const wasLoading = usePrevious(isLoading);
useEffect(() => {
// Only when a request finishes, not when one never started.
if (wasLoading && !isLoading) scrollToTop();
}, [isLoading, wasLoading]);The value updates after render, so during the render that changes it you still see the old one — which is the point. Do not use it to derive state you could compute directly.
API Reference
| Parameter | Type | Description |
|---|---|---|
value | T | The value to remember. |
Returns T | undefined — the previous render's value.