On this page

TypeScript React Apollo

GraphQL Code Generator plugin for TypeScript and React Apollo. Generates React Hooks and HOCs for your GraphQL operations.

Version
5.0.0
Weekly downloads
1.1M
License
MIT
Updated
Aug 17, 2026

Installation

          npm i -D @graphql-codegen/typescript-react-apollo
        

Config API Reference

withComponent

type: boolean

Customize the output by enabling/disabling the generated Component (deprecated since Apollo-Client v3). For more details: https://apollographql.com/docs/react/api/react/components Default value: “false”

withHOC

type: boolean

Customize the output by enabling/disabling the HOC (deprecated since Apollo-Client v3). For more details: https://apollographql.com/docs/react/api/react/hoc Default value: “false”

withHooks

type: boolean

Customized the output by enabling/disabling the generated React Hooks. For more details: https://apollographql.com/docs/react/api/react/hooks Default value: “true”

withMutationFn

type: boolean

Customized the output by enabling/disabling the generated mutation function signature. Default value: “true”

withRefetchFn

type: boolean

Enable generating a function to be used with refetchQueries Default value: “false”

apolloReactCommonImportFrom

type: string

Customize the package where apollo-react common lib is loaded from. Default value: “@apollo/react-common”

apolloReactComponentsImportFrom

type: string

Customize the package where apollo-react component lib is loaded from. Default value: “@apollo/react-components”

apolloReactHocImportFrom

type: string

Customize the package where apollo-react HOC lib is loaded from. Default value: “@apollo/react-hoc”

apolloReactHooksImportFrom

type: string

Customize the package where apollo-react hooks lib is loaded from. Default value: “@apollo/react-hooks”

componentSuffix

type: string

You can specify a suffix that gets attached to the name of the generated component. Default value: “Component”

reactApolloVersion

type: number

Sets the version of react-apollo. If you are using the old (deprecated) package of react-apollo, please set this configuration to 2. If you are using Apollo-Client v3, please set this to 3. Default value: “3”

withResultType

type: boolean

Customized the output by enabling/disabling the generated result type. Default value: “true”

withMutationOptionsType

type: boolean

Customized the output by enabling/disabling the generated mutation option type. Default value: “true”

withFragmentHooks

type: boolean

Whether or not to include wrappers for Apollo’s useFragment hook. Default value: “false”

addDocBlocks

type: boolean

Allows you to enable/disable the generation of docblocks in generated code. Some IDE’s (like VSCode) add extra inline information with docblocks, you can disable this feature if your preferred IDE does not. Default value: “true”

defaultBaseOptions

type: object

Configure default mutation and query hook options.

hooksSuffix

type: string

gqlImport

type: string

Customize from which module will gql be imported from. This is useful if you want to use modules other than graphql-tag, e.g. graphql.macro. Default value: “graphql-tag#gql”

documentNodeImport

type: string

Customize from which module will DocumentNode be imported from. This is useful if you want to use modules other than graphql, e.g. @graphql-typed-document-node. Default value: “graphql#DocumentNode”

noExport

type: boolean

Set this configuration to true if you wish to tell codegen to generate code with no export identifier. Default value: “false”

dedupeOperationSuffix

type: boolean

Set this configuration to true if you wish to make sure to remove duplicate operation name suffix. Default value: “false”

omitOperationSuffix

type: boolean

Set this configuration to true if you wish to disable auto add suffix of operation name, like Query, Mutation, Subscription, Fragment. Default value: “false”

operationResultSuffix

type: string

Adds a suffix to generated operation result type names Default value: ""

documentVariablePrefix

type: string

Changes the GraphQL operations variables prefix. Default value: ""

documentVariableSuffix

type: string

Changes the GraphQL operations variables suffix. Default value: “Document”

fragmentVariablePrefix

type: string

Changes the GraphQL fragments variables prefix. Default value: ""

fragmentVariableSuffix

type: string

Changes the GraphQL fragments variables suffix. Default value: “FragmentDoc”

documentMode

type: object

Declares how DocumentNode are created:

  • graphQLTag: graphql-tag or other modules (check gqlImport) will be used to generate document nodes. If this is used, document nodes are generated on client side i.e. the module used to generate this will be shipped to the client
  • documentNode: document nodes will be generated as objects when we generate the templates.
  • documentNodeImportFragments: Similar to documentNode except it imports external fragments instead of embedding them.
  • external: document nodes are imported from an external file. To be used with importDocumentNodeExternallyFrom

Note that some plugins (like typescript-graphql-request) also supports string for this parameter. Default value: “graphQLTag”

optimizeDocumentNode

type: boolean

If you are using documentMode: documentNode | documentNodeImportFragments, you can set this to true to apply document optimizations for your GraphQL document. This will remove all “loc” and “description” fields from the compiled document, and will remove all empty arrays (such as directives, arguments and variableDefinitions). Default value: “true”

importOperationTypesFrom

type: string

This config is used internally by presets, but you can use it manually to tell codegen to prefix all base types that it’s using. This is useful if you wish to generate base types from typescript-operations plugin into a different file, and import it from there. Default value: ""

importDocumentNodeExternallyFrom

type: string

This config should be used if documentMode is external. This has 2 usage:

  • any string: This would be the path to import document nodes from. This can be used if we want to manually create the document nodes e.g. Use graphql-tag in a separate file and export the generated document
  • ‘near-operation-file’: This is a special mode that is intended to be used with near-operation-file preset to import document nodes from those files. If these files are .graphql files, we make use of webpack loader. Default value: ""

pureMagicComment

type: boolean

This config adds PURE magic comment to the static variables to enforce treeshaking for your bundler. Default value: “false”

experimentalFragmentVariables

type: boolean

If set to true, it will enable support for parsing variables on fragments. Default value: “false”

strictScalars

type: boolean

Makes scalars strict.

If scalars are found in the schema that are not defined in scalars an error will be thrown during codegen. Default value: “false”

defaultScalarType

type: string

Allows you to override the type that unknown scalars will have. Default value: “any”

scalars

type: object

Extends or overrides the built-in scalars and custom GraphQL scalars to a custom type.

namingConvention

type: object

Allow you to override the naming convention of the output. You can either override all namings, or specify an object with specific custom naming convention per output. The format of the converter must be a valid module#method. Allowed values for specific output are: typeNames, enumValues. You can also use “keep” to keep all GraphQL names as-is. Additionally, you can set transformUnderscore to true if you want to override the default behavior, which is to preserve underscores.

Available case functions in change-case-all are camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, lowerCase, localeLowerCase, lowerCaseFirst, spongeCase, titleCase, upperCase, localeUpperCase and upperCaseFirst See more Default value: “change-case-all#pascalCase”

typesPrefix

type: string

Prefixes all the generated types. Default value: ""

typesSuffix

type: string

Suffixes all the generated types. Default value: ""

skipTypename

type: boolean

Does not add __typename to the generated types, unless it was specified in the selection set. Default value: “false”

nonOptionalTypename

type: boolean

Automatically adds __typename field to the generated types, even when they are not specified in the selection set, and makes it non-optional Default value: “false”

useTypeImports

type: boolean

Will use import type {} rather than import {} when importing only types. This gives compatibility with TypeScript’s “importsNotUsedAsValues”: “error” option Default value: “false”

inlineFragmentTypes

type: string

Whether fragment types should be inlined into other operations. “inline” is the default behavior and will perform deep inlining fragment types within operation type definitions. “combine” is the previous behavior that uses fragment type references without inlining the types (and might cause issues with deeply nested fragment that uses list types). “mask” transforms the types for use with fragment masking. Useful when masked types are needed when not using the “client” preset e.g. such as combining it with Apollo Client’s data masking feature. Default value: “inline”

emitLegacyCommonJSImports

type: boolean

Emit legacy common js imports. Default it will be true this way it ensure that generated code works with non-compliant bundlers. Default value: “true”

importExtension

type: object

Append this extension to all imports. Useful for ESM environments that require file extensions in import statements.

extractAllFieldsToTypes

type: boolean

Extract all field types to their own types, instead of inlining them. This helps to reduce type duplication, and makes type errors more readable. It can also significantly reduce the size of the generated code, the generation time, and the typechecking time. Default value: “false”

printFieldsOnNewLines

type: boolean

If you prefer to have each field in generated types printed on a new line, set this to true. This can be useful for improving readability of the resulting types, without resorting to running tools like Prettier on the output. Default value: “false”

includeExternalFragments

type: boolean

Whether to include external fragments in the generated code. External fragments are not defined in the same location as the operation definition. Default value: “false”

Usage Example

With React Hooks

For the given input:

query Test {
  feed {
    id
    commentCount
    repository {
      full_name
      html_url
      owner {
        avatar_url
      }
    }
  }
}

And the following configuration:

codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: 'YOUR_SCHEMA_HERE',
  documents: './src/**/*.graphql',
  generates: {
    './generated-types.ts': {
      plugins: ['typescript-operations', 'typescript-react-apollo']
    }
  }
}
export default config

Codegen will pre-compile the GraphQL operation into a DocumentNode object, and generate a ready-to-use React Hook for each operation you have.

In your application code, you can import it from the generated file, and use the React Hook in your component code:

import { useTest } from './generated-types'

export const MyComponent: React.FC = () => {
  const { data, error, loading } = useTest()

  return <div>…</div>
}

Generate Data Component

Codegen also supports generating data Components (deprecated in @apollo/client v3), you can turn it on this way:

codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: 'YOUR_SCHEMA_HERE',
  documents: './src/**/*.graphql',
  generates: {
    './generated-types.ts': {
      plugins: ['typescript-operations', 'typescript-react-apollo'],
      config: {
        withComponent: true
      }
    }
  }
}
export default config

Generate HOC

Codegen also supports generating High-Order-Components (deprecated in @apollo/client v3), you can turn it on this way:

codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: 'YOUR_SCHEMA_HERE',
  documents: './src/**/*.graphql',
  generates: {
    './generated-types.ts': {
      plugins: ['typescript-operations', 'typescript-react-apollo'],
      config: {
        withHOC: true
      }
    }
  }
}
export default config