-
Notifications
You must be signed in to change notification settings - Fork 0
usePrevious
Access the previous render's value of a state or prop variable. This is highly useful when you need to execute side effects comparing how a value changed over time.
Comparing the current state with the state from the immediately preceding render cycle.
import { useState } from "react";
import { usePrevious } from "react-hook-lab";
function CounterLog() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<div>
<p>Current Count: {count}</p>
{/* On the very first render, prevCount will be undefined */}
<p>Previous Count: {prevCount !== undefined ? prevCount : "None"}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}Using a strict default fallback for the initial render so the hook never returns undefined.
import { useState, useEffect } from "react";
import { usePrevious } from "react-hook-lab";
function SearchTracker() {
const [query, setQuery] = useState("");
// We pass "" as the second argument, ensuring the return type is purely string
const prevQuery = usePrevious(query, "");
useEffect(() => {
if (prevQuery !== query) {
console.log(`User changed search from "${prevQuery}" to "${query}"`);
}
}, [query, prevQuery]);
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}Detecting deep property changes on complex objects or props without firing deep equality checks manually.
import { usePrevious } from "react-hook-lab";
function ProfileEditor({ user }: { user: { id: string; role: string } }) {
const prevUser = usePrevious(user);
if (prevUser && prevUser.role !== user.role) {
console.log(`Role escalated from ${prevUser.role} to ${user.role}!`);
}
return <div>Editing {user.id}</div>;
}-
value- Type:
T - Description: The state, prop, or derived value to track across renders.
- Type:
-
defaultValue(Optional)- Type:
T - Description: An optional default value returned strictly on the first component render before a previous value exists.
- Type:
Returns the previous value of type T. If no defaultValue is provided, it returns T | undefined for the very first render.
The hook utilizes a combination of React's useRef and useEffect.
Because useEffect always executes after the component has painted and rendered, the useRef retains the old value during the current render phase.
Once the render finishes, the useEffect fires and updates the internal useRef to hold the new value.
This clever misalignment in timing ensures that whenever the component renders, the ref still holds the data from the immediately preceding cycle.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM