Skip to main content

Function: usePrevious()

@arolariu/components


@arolariu/components / usePrevious

Function: usePrevious()

usePrevious<T>(value): T

Defined in: hooks/usePrevious.tsx:36

Tracks and returns the previous value of a state or prop.

Type Parameters

T

T

The type of the value being tracked.

Parameters

value

T

The current value to track.

Returns

T

The value from the previous render, or undefined on the first render.

Remarks

This hook stores the value from the previous render cycle, allowing you to compare current and previous values. On the initial render, it returns undefined since there is no previous value yet.

Useful for detecting changes, implementing undo functionality, or creating animations based on value transitions.

Example

function Counter() {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);

return (
<div>
<p>Current: {count}</p>
<p>Previous: {previousCount ?? "N/A"}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// was this page useful?