Skip to main content

usePrevValue

Tracks the previous value of a state or prop. Returns undefined on the first render, then the value from the previous render cycle. Used internally by the Popover component.

Import

import { usePrevValue } from '@andrejground/lab';

Usage

import React from 'react';
import { usePrevValue } from '@andrejground/lab';

export default function App() {
const [count, setCount] = React.useState(0);
const prevCount = usePrevValue(count);

return (
<div>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
<p>Current: {count}</p>
<p>Previous: {prevCount ?? 'N/A'}</p>
</div>
);
}

API

const previousValue = usePrevValue(value);
ParameterTypeDescription
valueTThe value to track

Returns

TypeDescription
T | undefinedThe value from the previous render, or undefined on the first render