HooksusePrevious

usePrevious()

The usePrevious() hook stores the previous value of a state or prop. It is useful for comparing values between renders, detecting direction of changes, or triggering effects only when a value changes in a specific way.

Import

typescript
import { usePrevious } from 'the-react-hooks';

Usage

Current Value0
Previous Value
-
Component.tsx
import { usePrevious } from 'the-react-hooks';
import { useState } from 'react';

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

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

API

Arguments

  • value T The value to track.

Returns

Returns the previous value of type T | undefined. On the first render, it returns undefined.