• Custom React hook that returns the previous value of a state or prop.

    This hook stores the previous value of the provided input and allows you to access it in subsequent renders. If an initial value is provided, it will return that value before the first render.

    Example

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

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

    Type Parameters

    • T

    Parameters

    • value: T

      The current value to track.

    Returns T | undefined

  • Custom React hook that returns the previous value of a state or prop.

    This hook stores the previous value of the provided input and allows you to access it in subsequent renders. If an initial value is provided, it will return that value before the first render.

    Example

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

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

    Type Parameters

    • T

    • I

    Parameters

    • value: T

      The current value to track.

    • initialValue: I

      The initial value to return before the first render.

    Returns T | I