# usePreviousValue

Returns the previous value of a given variable, useful for comparing current and previous states in effects or for tracking changes over time.

## Import

```tsx
import { usePreviousValue } from '@coinbase/cds-common/hooks/usePreviousValue'
```

## API

### Parameters

The `usePreviousValue` hook accepts a single parameter:

- `value: T` - The value to track. Can be of any type.

### Returns

Returns the previous value of type `T | undefined`:

- Returns `undefined` on the first render
- Returns the previous value of the tracked value on subsequent renders

:::tip
This hook is useful for comparing the current value with its previous state, such as in animations, transitions, or when you need to react to value changes. The hook uses a ref to store the previous value, ensuring it persists between renders.
:::

## Examples

### Basic usage

```tsx live
function Example() {
  const [count, setCount] = useState(0);
  const previousCount = usePreviousValue(count);

  return (
    <VStack gap={3} alignItems="start">
      <VStack gap={1}>
        <Text font="headline">Current count: {count}</Text>
        <Text font="headline">Previous count: {previousCount ?? 'None'}</Text>
      </VStack>
      <Button onClick={() => setCount(count + 1)}>Increment</Button>
    </VStack>
  );
}
```

### With Complex Values

```tsx live
function Example() {
  const [user, setUser] = useState({ name: 'John', age: 25 });
  const previousUser = usePreviousValue(user);

  const updateAge = () => {
    setUser((prev) => ({ ...prev, age: prev.age + 1 }));
  };

  return (
    <VStack gap={3} alignItems="start">
      <VStack gap={1}>
        <Text font="headline">Name: {user.name}</Text>
        <Text font="headline">Age: {user.age}</Text>
        <Text font="headline">Previous age: {previousUser?.age ?? 'None'}</Text>
      </VStack>
      <Button onClick={updateAge}>Add Year</Button>
    </VStack>
  );
}
```

