# React

`@unicep/react` gives you the `useCep` hook, for React 18 or newer.

```bash
npm install @unicep/react
```

```bash
pnpm add @unicep/react
```

```bash
yarn add @unicep/react
```

```bash
bun add @unicep/react
```

`@unicep/core` is installed with it.

## Usage

```tsx
import { useState } from 'react';
import { useCep } from '@unicep/react';

export function CepField() {
  const [value, setValue] = useState('');
  const { data, error, isLoading } = useCep(value);

  return (
    <>
      <input value={value} onChange={(e) => setValue(e.target.value)} placeholder="00000-000" />
      {isLoading && <p>Searching…</p>}
      {error && <p>{error.message}</p>}
      {data && (
        <p>
          {data.street}, {data.neighborhood} - {data.city}/{data.state}
        </p>
      )}
    </>
  );
}
```

The hook only looks up when the value is a valid CEP (with or without the hyphen), so you can wire it straight to a text field. If the CEP changes, the previous result is dropped and the in-flight request is cancelled.

## API

```ts
useCep(cep: string | null | undefined, options?: {
  unicep?: Unicep;    // default: shared instance with all built-in providers
  enabled?: boolean;  // false pauses lookups, default true
}): {
  data: Address | undefined;
  error: Error | undefined;
  isLoading: boolean; // true while a lookup for the current valid CEP is in flight
}
```

`error` is one of the [unicep errors](/en/docs/errors), such as `CepNotFoundError` or
`AllProvidersFailedError`.

## Custom providers and options

```tsx
import { Unicep, viaCep, brasilApi } from '@unicep/core';

// Create it once, outside the component, so you do not lose the circuit breaker state.
const unicep = new Unicep({
  providers: [viaCep(), brasilApi()],
  timeoutMs: 3000,
  cache: {},
});

const { data } = useCep(value, { unicep });
```

Every option is covered in [Providers](/en/docs/providers) and [Core](/en/docs/core).