What is @graphql-codegen/client-preset?
The @graphql-codegen/client-preset package is part of the GraphQL Code Generator ecosystem, designed to automatically generate ready-to-use, type-safe query and mutation hooks, as well as TypeScript types for your GraphQL operations. It streamlines the development process by generating code that integrates seamlessly with popular GraphQL client libraries, such as Apollo Client, URQL, and others. This preset is particularly useful for projects that use GraphQL for data fetching and manipulation, as it minimizes the need for manually writing boilerplate code and ensures type safety across your client-side data operations.
What are @graphql-codegen/client-preset's main functionalities?
TypeScript Types Generation
Automatically generates TypeScript types for your GraphQL queries, mutations, and subscriptions based on your schema. This feature ensures type safety and autocompletion in your IDE, making it easier to work with GraphQL data in a TypeScript project. The code sample shows how to add a script to your package.json to run the code generation process.
"scripts": {
"generate": "graphql-codegen"
}
Hooks Generation for Apollo Client
Generates custom React hooks for your GraphQL operations when using Apollo Client. This allows you to easily execute queries and mutations with built-in loading, error, and data states. The code sample demonstrates how to import and use the generated hooks in a React component.
import { useMyQuery, useMyMutation } from './generated/graphql';
function MyComponent() {
const { data, loading, error } = useMyQuery();
const [mutate, { data: mutationData }] = useMyMutation();
// Use the hooks in your component
}
Document Nodes Generation
Generates GraphQL document nodes from your operations, which can be used with any GraphQL client library. This is useful for projects that might not use Apollo Client or URQL but still want to benefit from type-safe GraphQL operations. The code sample shows how to import and use the generated document nodes.
import { MY_QUERY_DOCUMENT, MY_MUTATION_DOCUMENT } from './generated/graphql';
// Use the document nodes with any GraphQL client
Other packages similar to @graphql-codegen/client-preset
graphql-code-generator
This is the core package of the GraphQL Code Generator ecosystem, of which @graphql-codegen/client-preset is a part. It provides the underlying functionality and plugin system for code generation but requires more configuration to achieve the same results as the client-preset.
type-graphql
Focuses on generating GraphQL schema and resolvers using TypeScript classes and decorators. While it serves a different part of the GraphQL ecosystem, focusing on server-side schema generation, it shares the goal of leveraging TypeScript for better development experience.