Which is Better GraphQL Client Libraries for React?
graphql-tag vs apollo-client vs react-apollo
1 Year
graphql-tagapollo-clientreact-apolloSimilar Packages:
What's GraphQL Client Libraries for React?

GraphQL client libraries are essential tools for managing data fetching and state management in applications that use GraphQL as their API. These libraries provide developers with the means to interact with GraphQL servers, handle queries and mutations, and manage local state in a seamless manner. They simplify the process of integrating GraphQL into React applications, allowing for efficient data management and improved performance. Understanding the differences between these libraries is crucial for selecting the right tool for your project's needs.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
graphql-tag6,554,1542,323-993 years agoMIT
apollo-client427,75119,363-5164 years agoMIT
react-apollo105,3296,851-2055 years agoMIT
Feature Comparison: graphql-tag vs apollo-client vs react-apollo

Data Fetching

  • graphql-tag: GraphQL Tag is a simple utility that allows you to define GraphQL queries as template literals in your JavaScript code. It does not handle data fetching itself but is used in conjunction with other libraries like Apollo Client to parse and validate queries. It is lightweight and straightforward, making it easy to integrate into any JavaScript project.
  • apollo-client: Apollo Client provides a powerful and flexible way to fetch data from a GraphQL server. It supports various fetching strategies, including query batching, polling, and subscriptions, allowing developers to tailor data fetching to their application's needs. Apollo Client also manages caching automatically, optimizing data retrieval and minimizing network requests.
  • react-apollo: React Apollo integrates Apollo Client with React, providing components and hooks that simplify data fetching in React applications. It allows developers to use declarative data fetching with components like Query and Mutation, making it easy to manage data and UI state in a React-friendly way.

State Management

  • graphql-tag: GraphQL Tag does not provide state management features on its own. It is primarily focused on defining and parsing GraphQL queries. Developers typically use it alongside a state management solution or a GraphQL client to handle application state effectively.
  • apollo-client: Apollo Client excels in state management by allowing developers to manage both local and remote data in a unified way. It provides a normalized cache that helps in managing the state of your application efficiently, enabling features like optimistic UI updates and automatic cache updates based on server responses.
  • react-apollo: React Apollo leverages Apollo Client's caching capabilities to manage state in React applications. It provides hooks like useQuery and useMutation that help manage local state alongside remote data, making it easier to synchronize UI with the application state.

Learning Curve

  • graphql-tag: GraphQL Tag is very easy to learn and use. It requires minimal setup and can be quickly integrated into any JavaScript project. Its simplicity makes it an excellent choice for developers who want to start using GraphQL without the overhead of a full client library.
  • apollo-client: Apollo Client has a moderate learning curve due to its extensive feature set and configuration options. Developers need to understand concepts like caching, query normalization, and how to set up the client properly to take full advantage of its capabilities. However, once mastered, it offers powerful tools for managing GraphQL data.
  • react-apollo: React Apollo is relatively easy to learn for developers familiar with React. It provides a set of hooks and components that align well with React's declarative approach, making it intuitive to use. However, understanding how it interacts with Apollo Client's caching and state management may require some additional learning.

Integration

  • graphql-tag: GraphQL Tag is a standalone utility that can be used with any JavaScript library or framework. It does not impose any specific architecture or design pattern, allowing developers to use it in a way that best fits their project needs.
  • apollo-client: Apollo Client can be integrated with various frameworks and libraries beyond React, including Angular, Vue, and even vanilla JavaScript applications. This flexibility makes it a versatile choice for projects that may evolve or require integration with multiple technologies.
  • react-apollo: React Apollo is specifically designed for React applications, providing seamless integration with React's component model. It offers a set of React-specific APIs that make it easy to fetch and manage data within React components, enhancing the developer experience.

Community and Ecosystem

  • graphql-tag: GraphQL Tag is part of the Apollo ecosystem, benefiting from the same community support and resources. While it is simpler and has a narrower focus, it is widely used in conjunction with Apollo Client, making it easy to find help and examples online.
  • apollo-client: Apollo Client has a large and active community, with extensive documentation, tutorials, and third-party resources available. Its popularity means that developers can find a wealth of information and support when working with the library, making it easier to troubleshoot issues and learn best practices.
  • react-apollo: React Apollo is also part of the Apollo ecosystem, and it shares the same community support and resources. The integration with Apollo Client means that developers can leverage the extensive documentation and community knowledge available for both libraries.
How to Choose: graphql-tag vs apollo-client vs react-apollo
  • graphql-tag: Choose GraphQL Tag if you want a lightweight solution for parsing GraphQL queries in your JavaScript code. It is particularly useful for embedding GraphQL queries directly in your components without needing a full client library, making it a good choice for smaller projects or when you want more control over your data fetching.
  • apollo-client: Choose Apollo Client if you need a comprehensive solution that supports caching, optimistic UI updates, and advanced features like pagination and subscriptions. It is ideal for applications that require robust data management and integration with various UI frameworks.
  • react-apollo: Choose React Apollo if you are building a React application and want to leverage Apollo Client's features with a set of React-specific components and hooks. It simplifies the integration of Apollo Client with React, making it easier to manage data fetching and state in your components.
README for graphql-tag

graphql-tag

npm version Build Status Get on Slack

Helpful utilities for parsing GraphQL queries. Includes:

  • gql A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.
  • /loader A webpack loader to preprocess queries

graphql-tag uses the reference graphql library under the hood as a peer dependency, so in addition to installing this module, you'll also have to install graphql.

gql

The gql template literal tag can be used to concisely write a GraphQL query that is parsed into a standard GraphQL AST. It is the recommended method for passing queries to Apollo Client. While it is primarily built for Apollo Client, it generates a generic GraphQL AST which can be used by any GraphQL client.

import gql from 'graphql-tag';

const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
`

The above query now contains the following syntax tree.

{
  "kind": "Document",
  "definitions": [
    {
      "kind": "OperationDefinition",
      "operation": "query",
      "name": null,
      "variableDefinitions": null,
      "directives": [],
      "selectionSet": {
        "kind": "SelectionSet",
        "selections": [
          {
            "kind": "Field",
            "alias": null,
            "name": {
              "kind": "Name",
              "value": "user",
              ...
            }
          }
        ]
      }
    }
  ]
}

Fragments

The gql tag can also be used to define reusable fragments, which can easily be added to queries or other fragments.

import gql from 'graphql-tag';

const userFragment = gql`
  fragment User_user on User {
    firstName
    lastName
  }
`

The above userFragment document can be embedded in another document using a template literal placeholder.

const query = gql`
  {
    user(id: 5) {
      ...User_user
    }
  }
  ${userFragment}
`

Note: While it may seem redundant to have to both embed the userFragment variable in the template literal AND spread the ...User_user fragment in the graphQL selection set, this requirement makes static analysis by tools such as eslint-plugin-graphql possible.

Why use this?

GraphQL strings are the right way to write queries in your code, because they can be statically analyzed using tools like eslint-plugin-graphql. However, strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff.

That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql tag.

Caching parse results

This package only has one feature - it caches previous parse results in a simple dictionary. This means that if you call the tag on the same query multiple times, it doesn't waste time parsing it again. It also means you can use === to compare queries to check if they are identical.

Importing graphQL files

To add support for importing .graphql/.gql files, see Webpack loading and preprocessing below.

Given a file MyQuery.graphql

query MyQuery {
  ...
}

If you have configured the webpack graphql-tag/loader, you can import modules containing graphQL queries. The imported value will be the pre-built AST.

import MyQuery from 'query.graphql'

Importing queries by name

You can also import query and fragment documents by name.

query MyQuery1 {
  ...
}

query MyQuery2 {
  ...
}

And in your JavaScript:

import { MyQuery1, MyQuery2 } from 'query.graphql'

Preprocessing queries and fragments

Preprocessing GraphQL queries and fragments into ASTs at build time can greatly improve load times.

Babel preprocessing

GraphQL queries can be compiled at build time using babel-plugin-graphql-tag. Pre-compiling queries decreases script initialization time and reduces bundle sizes by potentially removing the need for graphql-tag at runtime.

TypeScript preprocessing

Try this custom transformer to pre-compile your GraphQL queries in TypeScript: ts-transform-graphql-tag.

React Native and Next.js preprocessing

Preprocessing queries via the webpack loader is not always possible. babel-plugin-import-graphql supports importing graphql files directly into your JavaScript by preprocessing GraphQL queries into ASTs at compile-time.

E.g.:

import myImportedQuery from './productsQuery.graphql'

class ProductsPage extends React.Component {
  ...
}

Webpack loading and preprocessing

Using the included graphql-tag/loader it is possible to maintain query logic that is separate from the rest of your application logic. With the loader configured, imported graphQL files will be converted to AST during the webpack build process.

Example webpack configuration

{
  ...
  loaders: [
    {
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader'
    }
  ],
  ...
}

Create React App

Preprocessing GraphQL imports is supported in create-react-app >= v2 using evenchange4/graphql.macro.

For create-react-app < v2, you'll either need to eject or use react-app-rewire-inline-import-graphql-ast.

Testing

Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.

Support for fragments

With the webpack loader, you can import fragments by name:

In a file called query.gql:

fragment MyFragment1 on MyType1 {
  ...
}

fragment MyFragment2 on MyType2 {
  ...
}

And in your JavaScript:

import { MyFragment1, MyFragment2 } from 'query.gql'

Note: If your fragment references other fragments, the resulting document will have multiple fragments in it. In this case you must still specify the fragment name when using the fragment. For example, with @apollo/client you would specify the fragmentName option when using the fragment for cache operations.

Warnings

This package will emit a warning if you have multiple fragments of the same name. You can disable this with:

import { disableFragmentWarnings } from 'graphql-tag';

disableFragmentWarnings()

Experimental Fragment Variables

This package exports an experimentalFragmentVariables flag that allows you to use experimental support for parameterized fragments.

You can enable / disable this with:

import { enableExperimentalFragmentVariables, disableExperimentalFragmentVariables } from 'graphql-tag';

Enabling this feature allows you declare documents of the form

fragment SomeFragment ($arg: String!) on SomeType {
  someField
}

Resources

You can easily generate and explore a GraphQL AST on astexplorer.net.