npm package: @softonus/graphql-codegen-apollo-hooks
Description: GraphQL Code Generator plugin that generates Apollo Client v4 hooks with full type inference. Replacement for deprecated typescript-react-apollo
Author: Ebo
Latest version: 1.1.0

# @softonus/graphql-codegen-apollo-hooks

> **Generate Apollo Client v4 hooks from your GraphQL operations automatically**

[![npm version](https://img.shields.io/npm/v/@softonus/graphql-codegen-apollo-hooks)](https://www.npmjs.com/package/@softonus/graphql-codegen-apollo-hooks)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## What is this?

`@softonus/graphql-codegen-apollo-hooks` is a GraphQL Code Generator plugin that **automatically generates Apollo Client v4 hooks** from your GraphQL query and mutation files.

It's the **official replacement for the deprecated `typescript-react-apollo`** plugin which only works with Apollo Client v3.

## Why do I need this?

If you're using Apollo Client v4, the old `typescript-react-apollo` plugin won't work. This plugin fills that gap by generating the same kind of auto-typed hooks but for Apollo v4.

## Installation

```bash
# npm
npm install @softonus/graphql-codegen-apollo-hooks

# yarn
yarn add @softonus/graphql-codegen-apollo-hooks

# pnpm
pnpm add @softonus/graphql-codegen-apollo-hooks

# bun
bun add @softonus/graphql-codegen-apollo-hooks
```

## Quick Start

```yaml
# codegen.ts
import { CodegenConfig } from '@graphql-codegen/cli'
import { readdirSync } from 'fs'

const scalars = {
  ID: 'string', String: 'string', Int: 'number', Boolean: 'boolean',
  Float: 'number', JSON: '{ [key: string]: any }', Upload: 'File',
  DateTime: 'string', Email: 'string', PhoneNumber: 'string'
}

const modules = readdirSync('gql', { withFileTypes: true })
  .filter(d => d.isDirectory())
  .map(d => d.name)

const config: CodegenConfig = {
  schema: 'http://localhost:4000/graphql',
  documents: 'gql/**/*.gql',
  generates: modules.reduce((acc, module) => ({
    ...acc,
    [`gql/${module}/graphql.ts`]: {
      schema: 'http://localhost:4000/graphql',
      documents: `gql/${module}/**/*.gql`,
      plugins: ['typescript', 'typescript-operations', 'typed-document-node'],
      config: { scalars, useTypeImports: true }
    },
    [`gql/${module}/hooks.ts`]: {
      schema: 'http://localhost:4000/graphql',
      documents: `gql/${module}/**/*.gql`,
      plugins: ['@softonus/graphql-codegen-apollo-hooks']
    }
  }), {})
}

export default config
```

## What it generates

Given a GraphQL file `gql/auth/signIn.gql`:

```graphql
mutation SignIn($input: SignInInput!) {
  signIn(input: $input)
}
```

It generates `gql/auth/hooks.ts`:

```typescript
/* eslint-disable */
/**
 * @softonus/graphql-codegen-apollo-hooks
 * Generated by graphql-codegen
 */

import { useMutation } from '@apollo/client/react'
import { SignInDocument, SignInMutation, SignInMutationVariables } from '@/gql/auth/graphql'

/**
 * Hook for `SignIn` mutation.
 * @see {@link https://www.apollographql.com/docs/react/data/mutations/}
 * @param baseOptions - MutationOptions for useMutation.
 */
export function useSignInMutation(baseOptions?: Pick<import('@apollo/client/react').useMutation.Options<SignInMutation, SignInMutationVariables>, 'variables' | 'optimisticResponse' | 'refetchQueries' | 'awaitRefetchQueries' | 'update' | 'onCompleted' | 'onError' | 'onQueryUpdated' | 'fetchPolicy' | 'errorPolicy' | 'context'>) {
  return useMutation<SignInMutation, SignInMutationVariables>(SignInDocument, baseOptions)
}
```

## Usage in Components

```tsx
import { useSignInMutation } from '@/gql/auth/hooks'

function LoginForm() {
  const [signIn] = useSignInMutation()

  const handleSubmit = async (values) => {
    const { data } = await signIn({ variables: { input: values } })
    // data is fully typed! ✓
  }
}
```

## Comparison

| Feature | typescript-react-apollo (v3) | @softonus/graphql-codegen-apollo-hooks (v4) |
|---------|------------------------------|-------------------|
| Apollo v4 support | ❌ No | ✅ Yes |
| Auto-generated hooks | ✅ Yes | ✅ Yes |
| Type inference | ✅ Full | ✅ Full |
| Per-module output | ❌ No | ✅ Yes |
| Tree-shakeable | ❌ No | ✅ Yes |
| Typed options + JSDoc | ❌ No | ✅ Yes (typed return, JSDoc) |
| JSDoc comments | ❌ No | ✅ Yes |
| Lazy query variants | ❌ No | ✅ Yes (opt-in) |
| Suspense variants | ❌ No | ✅ Yes (opt-in) |

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `hookPrefix` | `string` | `'use'` | Prefix for hook names |
| `apolloReactImportFrom` | `string` | `'@apollo/client/react'` | Import path for hooks |
| `groupByModule` | `boolean` | `true` | Group hooks by folder |
| `module` | `string` | `undefined` | Only generate hooks for this specific module |
| `generateLazyQuery` | `boolean` | `false` | Also generate `useXxxLazy()` variants for queries |
| `generateSuspenseQuery` | `boolean` | `false` | Also generate `useXxxSuspense()` variants for queries |

## FAQ

**Q: How is this different from `typed-document-node`?**
A: `typed-document-node` only generates typed `DocumentNode` objects. This plugin generates ready-to-use hooks that wrap those documents.

**Q: Can I use this with React Query or URQL?**
A: No, this plugin specifically generates Apollo Client v4 hooks. For other clients, you'd need their respective hook generators.

**Q: Does it support subscriptions?**
A: Yes! It generates `useSubscription` hooks for subscription operations.

**Q: How do I migrate from `typescript-react-apollo`?**
A: Replace `typescript-react-apollo` with `@softonus/graphql-codegen-apollo-hooks` in your codegen config and Apollo Client v4 will automatically be used.

## Example Output Structure

```
gql/
├── auth/
│   ├── graphql.ts      # Types + DocumentNodes
│   └── hooks.ts       # useSignIn, useSignUp, useMe, etc.
├── posts/
│   ├── graphql.ts
│   └── hooks.ts       # usePosts, useCreatePost, etc.
└── memorial/
    ├── graphql.ts
    └── hooks.ts       # useMemorials, useCreateMemorial, etc.
```

## License

MIT © [Ebo](https://github.com/ebokoo)