⬡ GraphQL Intermediate

What is the graphql-tag (gql) utility?

Answer

gql is a tagged template literal function from the graphql-tag package (also exported from @apollo/client) that parses GraphQL query strings into AST document nodes. Usage: const GET_USER = gql\`query GetUser($id: ID!) { user(id: $id) { name email } }\`;. Benefits: (1) Compile-time parsing: the query is parsed once when the module loads, not on every render. (2) Syntax validation: IDEs with GraphQL plugins highlight errors in gql template literals. (3) Fragment composition: gql\`query { ...${USER_FIELDS} }\` for fragment spreading. (4) Code generation: GraphQL Code Generator uses gql-tagged queries to generate TypeScript types. (5) Tooling support: Apollo DevTools recognizes gql-parsed queries. Store queries in .graphql files (better IDE support) and import them, or use the tagged template approach inline.