A React hook that stores the previous value of a variable.

This hook uses a ref to keep track of the previous value of the provided variable. On every update, the current value is stored so that the previous value is accessible.

import React, { useState } from "react";
import { usePrevious } from "essential-hooks-collection";

const MyComponent = () => {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);

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

export default MyComponent;
  • Type Parameters

    • T

      The type of the value.

    Parameters

    • value: T

      The current value.

    Returns undefined | T

    The previous value before the last update, or undefined if not available.