Skip to main content

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

ParameterTypeDefaultDescription
valueTThe current value to track.

Return Value

PropertyTypeDescription
previousValueT | nullThe previous value before the last update, or null if no previous value exists yet.

Behavior

  • Returns null on the initial render, before any previous value exists.
  • After each render, stores the current value so it can be returned on the next render.
  • Updates the tracked value via an effect, so the returned value reflects the value from the previous committed render.