Hooks
No hooks found in any category.
usePrevious
utilityInstallation
npx usehooks-cli@latest add use-previous
Description
A React hook that returns the previous value of a state or prop. Useful for comparing current and previous values in effects or for implementing undo functionality.
Parameters
Name | Type | Default | Description |
---|---|---|---|
value | T | - | The current value to track |
Examples
Comparing Previous and Current Values
Detecting changes between renders
1const [count, setCount] = useState(0);
2const previousCount = usePrevious(count);
3
4useEffect(() => {
5 if (previousCount !== undefined) {
6 console.log(`Count changed from ${previousCount} to ${count}`);
7
8 if (count > previousCount) {
9 console.log('Count increased');
10 } else if (count < previousCount) {
11 console.log('Count decreased');
12 }
13 }
14}, [count, previousCount]);
Conditional Effects
Running effects only when specific changes occur
1const [user, setUser] = useState(null);
2const previousUser = usePrevious(user);
3
4useEffect(() => {
5 // Only run when user actually changes (not on initial load)
6 if (previousUser && user?.id !== previousUser?.id) {
7 // User switched - clear cache, update analytics, etc.
8 clearUserCache();
9 trackUserSwitch(previousUser.id, user.id);
10 }
11}, [user, previousUser]);
Animation Triggers
Triggering animations based on value changes
1const [status, setStatus] = useState('idle');
2const previousStatus = usePrevious(status);
3const [shouldAnimate, setShouldAnimate] = useState(false);
4
5useEffect(() => {
6 if (previousStatus && previousStatus !== status) {
7 setShouldAnimate(true);
8
9 // Reset animation flag after animation completes
10 const timer = setTimeout(() => setShouldAnimate(false), 300);
11 return () => clearTimeout(timer);
12 }
13}, [status, previousStatus]);
14
15return (
16 <div className={shouldAnimate ? 'animate-pulse' : ''}>
17 Status: {status}
18 </div>
19);
Dependencies
react
Notes
- •Returns undefined on the first render since there's no previous value
- •Uses useRef to store the previous value without causing re-renders
- •The previous value is updated after the current render completes
- •Useful for implementing undo functionality or change detection
- •Works with any type of value including objects, arrays, and primitives
Implementation
1"use client";
2
3import { useRef, useEffect } from "react";
4
5export function usePrevious<T>(value: T): T | undefined {
6 const ref = useRef<T>(undefined);
7
8 useEffect(() => {
9 ref.current = value;
10 });
11
12 return ref.current;
13}
14
15export default usePrevious;
16