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 | Description |
---|---|---|
initialValue | generic | The initial value of the state. |
Return Value
usePrevious
returns a previousValue
to track