usePrevious
A hook that returns the previous value of a variable.
Overview
usePrevious stores the value from the previous render. It is commonly used to compare current props or state with their previous values to detect changes or trends.
Demo
API Reference
function usePrevious<T>(value: T): T | undefinedParameters
| Name | Type | Description |
|---|---|---|
value | T | The value to track. |
Usage Example
import { useState, useEffect } from 'react'
import { usePrevious } from 'react-hooks-ts'
function Counter() {
const [count, setCount] = useState(0)
const prevCount = usePrevious(count)
useEffect(() => {
if (prevCount !== undefined && count > prevCount) {
console.log('Count increased')
}
}, [count, prevCount])
return (
<div>
<p>Current: {count}</p>
<p>Previous: {prevCount}</p>
<button onClick={() => setCount(c => c + 1)}>+</button>
</div>
)
}