usePreviousState()
ts
function usePreviousState<T>(state, initialValue?): T | undefined;Defined in: previous.ts:31
React hook for getting the previous state value.
Type Parameters
| Type Parameter | Description |
|---|---|
T | Type of the state value. |
Parameters
| Parameter | Type | Description |
|---|---|---|
state | T | Current state value to track. |
initialValue? | T | Optional initial value for the previous state. If not provided, the previous state will be undefined on the first render. |
Returns
T | undefined
Previous state value of type T or undefined if it's the first render and no initial value is provided.
Example
tsx
function MyComponent () {
const [count, setCount] = useState(0);
const prevCount = usePreviousState(count);
return (
<>
<p>Current count: {count}</p>
<p>Previous count: {prevCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
)
}Since
1.0.0
Author
Simon Kovtyk