usePrevious
usePrevious is a custom React hook to store and retrieve the previous value of a given state or prop.
Usage
import { useState } from "react";
import { usePrevious } from "hookify-react";
export default function UsePreviousExample() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
console.log(`Previous count: ${prevCount}, Current count: ${count}`);
return (
<div>
<button onClick={() => setCount((prev) => prev + 1)}>+1</button>
<p>Current count value: <strong>{count}</strong></p>
<p>Previous count value: <strong>{prevCount}</strong></p>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
value | T | — | The current value to track. |
Return Value
| Property | Type | Description |
|---|---|---|
previousValue | T | null | The previous value before the last update, or null if no previous value exists yet. |
Behavior
- Returns
nullon the initial render, before any previous value exists. - After each render, stores the current
valueso it can be returned on the next render. - Updates the tracked value via an effect, so the returned value reflects the value from the previous committed render.