Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-react

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-react

A lightweight but powerful GraphQL client for React using modern context and hooks APIs; the first Relay and Apollo alternative with server side rendering.

  • 8.3.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.9K
increased by54.71%
Maintainers
1
Weekly downloads
 
Created
Source

graphql-react logo

graphql-react

npm version Build status

A lightweight but powerful GraphQL client for React using modern context and hooks APIs; the first Relay and Apollo alternative with server side rendering.

Apollo comparison

Bundle impact

graphql-react

A < 2.5 KB bundle impact is guaranteed by size-limit tests. The impact is smaller than the bundle size badge suggests as the internal object-assign dependency is shared with react.

DependencyInstall sizeBundle size
graphql-reactgraphql-react install sizegraphql-react minzipped size

Tree shaking bundlers will eliminate unused exports (perhaps reportCacheErrors).

Apollo

Several dependencies must be installed for a minimal Apollo project.

DependencyInstall sizeBundle size
apollo-boostapollo-boost install sizeapollo-boost minzipped size
react-apolloreact-apollo install sizereact-apollo minzipped size
graphql-taggraphql-tag install sizegraphql-tag minzipped size
graphqlgraphql install sizegraphql minzipped size

Tree shaking bundlers will eliminate unused graphql exports.

In addition, fragment matcher config impacts bundle size relative to the number and complexity of schema unions and interfaces; see Cache strategy.

Native ESM

graphql-react

Supports native ESM via .mjs files for Node.js in --experimental-modules mode and tree shaking bundlers like webpack. For legacy environments CJS is provided via .js files.

Apollo

No support for native ESM, although they do provide faux ESM via package module fields for tree shaking bundlers like webpack.

Writing queries

graphql-react

Uses template strings:

const QUERY = /* GraphQL */ `
  {
    viewer {
      id
    }
  }
`

The optional /* GraphQL */ comment signals the syntax for highlighters and linters.

Apollo

Uses template strings tagged with gql from graphql-tag:

import gql from 'graphql-tag'

const QUERY = gql`
  {
    viewer {
      id
    }
  }
`

Cache strategy

graphql-react

The GraphQL client has no GraphQL API specific config; fetch options are determined on demand at the component level. Multiple GraphQL APIs can be queried!

GraphQL operations are cached under hashes of their fetch options. Multiple operations with the same hash share the same loading status and cache value.

fetch, HTTP, parse and GraphQL errors can be cached, and therefore server side rendered and transported to the client for hydration and initial render.

Apollo

Apollo Client is configured for one GraphQL API per app.

GraphQL operation data is deconstructed based upon id and __typename fields into a “normalized” cache. These fields must be queried even if they aren’t used in components.

Errors aren’t cached, and therefore can’t be server side rendered and transported to the client for hydration and initial render.

Apollo Client must be configured with schema knowledge extracted at build time for a “fragment matcher” to cache fragments on unions and interfaces properly. It’s challenging to reconfigure and redeploy clients whenever the GraphQL schema updates. Also, the config increases the client bundle size; see Bundle impact.

Stale cache

graphql-react

By default, cache is refreshed for mounting components.

GraphQL operations can optionally refresh all cache except their own fresh cache; handy for mutations.

Apollo

By default, cache isn’t refreshed for mounting components.

GraphQL mutations only update the cache with the contents of their payload. The prescribed approach is to try to manually update other normalized cache after mutations using complicated and often buggy APIs. Resetting all cache is possible, but it also wipes the result of the last operation.

File uploads

graphql-react

Out of the box file uploads compliant with the GraphQL multipart request spec (authored by @jaydenseric) which is supported by popular GraphQL servers including Apollo Server. File input values can be used as query or mutation arguments.

Apollo

Supports file uploads if you drop apollo-boost and manually setup Apollo Client with apollo-upload-client (also by @jaydenseric).

Subscriptions

graphql-react

Not supported yet.

Apollo

Supported.

TypeScript

graphql-react

Written in ECMAScript; no types are exported.

Apollo

Written in TypeScript; types are exported.

Next.js integration

graphql-react

Has an official example using next-graphql-react, which provides easy an easy to install App decorator and plugin to enable server side rendered GraphQL queries.

Apollo

Has an official example, but it consists of over 100 lines of complicated copy-paste boilerplate code across multiple files.

Setup

Next.js setup

See the next-graphql-react setup instructions.

Vanilla React setup

To install graphql-react from npm run:

npm install graphql-react

Create a single GraphQL instance and use GraphQLProvider to provide it for your app.

For server side rendering see ssr().

Usage

Use the useGraphQL React hook in your components to make queries and mutations, or use the GraphQL instance method operate directly.

Examples

Support

Consider polyfilling:

API

Table of contents

class GraphQL

A lightweight GraphQL client that caches queries and mutations.

ParameterTypeDescription
optionsobject? = {}Options.
options.cacheGraphQLCache? = {}Cache to import; usually from a server side render.
See
Examples

Construct a GraphQL client.

import { GraphQL } from 'graphql-react'

const graphql = new GraphQL()
GraphQL instance method off

Removes an event listener.

ParameterTypeDescription
typestringEvent type.
handlerFunctionEvent handler.
GraphQL instance method on

Adds an event listener.

ParameterTypeDescription
typestringEvent type.
handlerFunctionEvent handler.
See
GraphQL instance method operate

Loads or reuses an already loading GraphQL operation in GraphQL operations. Emits a GraphQL instance fetch event if an already loading operation isn’t reused, and a cache event once it’s loaded into the GraphQL cache.

ParameterTypeDescription
optionsobjectOptions.
options.operationGraphQLOperationGraphQL operation.
options.fetchOptionsOverrideGraphQLFetchOptionsOverride?Overrides default GraphQL operation fetch options.
options.reloadOnLoadboolean? = falseShould a GraphQL reload happen after the operation loads, excluding the loaded operation cache.
options.resetOnLoadboolean? = falseShould a GraphQL reset happen after the operation loads, excluding the loaded operation cache.

Returns: GraphQLOperationLoading — Loading GraphQL operation details.

GraphQL instance method reload

Signals that GraphQL cache subscribers such as the useGraphQL React hook should reload their GraphQL operation. Emits a GraphQL instance reload event.

ParameterTypeDescription
exceptCacheKeyGraphQLCacheKey?A GraphQL cache key for cache to exempt from reloading.
Examples

Reloading the GraphQL cache.

graphql.reload()
GraphQL instance method reset

Resets the GraphQL cache, useful when a user logs out. Emits a GraphQL instance reset event.

ParameterTypeDescription
exceptCacheKeyGraphQLCacheKey?A GraphQL cache key for cache to exempt from deletion. Useful for resetting cache after a mutation, preserving the mutation cache.
Examples

Resetting the GraphQL cache.

graphql.reset()
GraphQL instance property cache

Cache of loaded GraphQL operations. You probably don’t need to interact with this unless you’re implementing a server side rendering framework.

Type: GraphQLCache

Examples

Export cache as JSON.

const exportedCache = JSON.stringify(graphql.cache)

Example cache JSON.

{
  "a1bCd2": {
    "data": {
      "viewer": {
        "name": "Jayden Seric"
      }
    }
  }
}
GraphQL instance property operations

A map of loading GraphQL operations. You probably don’t need to interact with this unless you’re implementing a server side rendering framework.

Type: object<GraphQLCacheKey, Promise<GraphQLCacheValue>>


function GraphQLProvider

A React component that provides a GraphQL instance for an app.

ParameterTypeDescription
propsobjectComponent props.
props.graphqlGraphQLGraphQL instance.
props.childrenReactNode?React children.

Returns: ReactNode — React virtual DOM node.

See
Examples

Provide a GraphQL instance for an app.

import { GraphQL, GraphQLProvider } from 'graphql-react'

const graphql = new GraphQL()

const App = ({ children }) => (
  <GraphQLProvider graphql={graphql}>{children}</GraphQLProvider>
)

function reportCacheErrors

A GraphQL cache event handler that reports fetch, HTTP, parse and GraphQL errors via console.log(). In a browser environment the grouped error details are expandable.

ParameterTypeDescription
dataobjectGraphQL cache event data.
data.cacheKeyGraphQLCacheKeyGraphQL cache key.
data.cacheValueGraphQLCacheKeyGraphQL cache value.
Examples

GraphQL initialized to report cache errors.

import { GraphQL, reportCacheErrors } from 'graphql-react'

const graphql = new GraphQL()
graphql.on('cache', reportCacheErrors)

function ssr

Asynchronously server side renders a React node, preloading all GraphQL queries set to loadOnMount. After resolving, cache can be exported from the GraphQL instance property cache for serialization (usually to JSON) and transport to the client for hydration via the GraphQL constructor parameter options.cache.

Be sure to globally polyfill fetch.

ParameterTypeDescription
graphqlGraphQLGraphQL instance.
nodeReactNodeReact virtual DOM node.
renderFunction? = ReactDOMServer.renderToStaticMarkupSynchronous React server side render function, defaulting to ReactDOMServer.renderToStaticMarkup as it is more efficient than ReactDOMServer.renderToString.

Returns: Promise<string> — Promise resolving the rendered HTML string.

See
Examples

SSR function that resolves a HTML string and cache JSON for client hydration.

import { GraphQL, GraphQLProvider } from 'graphql-react'
import { ssr } from 'graphql-react/server'
import ReactDOMServer from 'react-dom/server'
import { App } from './components'

async function render() {
  const graphql = new GraphQL()
  const page = (
    <GraphQLProvider graphql={graphql}>
      <App />
    </GraphQLProvider>
  )
  const html = await ssr(graphql, page, ReactDOMServer.renderToString)
  const cache = JSON.stringify(graphql.cache)
  return { html, cache }
}

SSR function that resolves a HTML string suitable for a static page.

import { GraphQL, GraphQLProvider } from 'graphql-react'
import { ssr } from 'graphql-react/server'
import { App } from './components'

function render() {
  const graphql = new GraphQL()
  const page = (
    <GraphQLProvider graphql={graphql}>
      <App />
    </GraphQLProvider>
  )
  return ssr(graphql, page)
}

function useGraphQL

A React hook to manage a GraphQL operation in a component.

ParameterTypeDescription
optionsobjectOptions.
options.fetchOptionsOverrideGraphQLFetchOptionsOverride?Overrides default fetch options for the GraphQL operation.
options.loadOnMountboolean? = trueShould the operation load when the component mounts.
options.loadOnReloadboolean? = trueShould the operation load when the GraphQL reload event fires, if the operation was not the one that caused the reload.
options.loadOnResetboolean? = trueShould the operation load when its GraphQL cache value is reset, if the operation was not the one that caused the reset.
options.reloadOnLoadboolean? = falseShould a GraphQL reload happen after the operation loads, excluding the loaded operation cache.
options.resetOnLoadboolean? = falseShould a GraphQL reset happen after the operation loads, excluding the loaded operation cache.
options.operationGraphQLOperationGraphQL operation.

Returns: GraphQLOperationStatus — GraphQL operation status.

See
Examples

A component that displays a Pokémon image.

import { useGraphQL } from 'graphql-react'

const PokemonImage = ({ name }) => {
  const { loading, cacheValue = {} } = useGraphQL({
    fetchOptionsOverride(options) {
      options.url = 'https://graphql-pokemon.now.sh'
    },
    operation: {
      query: `{ pokemon(name: "${name}") { image } }`
    }
  })

  return cacheValue.data ? (
    <img src={cacheValue.data.pokemon.image} alt={name} />
  ) : loading ? (
    'Loading…'
  ) : (
    'Error!'
  )
}

Options guide for common situations.

The defaults are suitable for typical query use, as apps tend to have more queries than mutations.

SituationloadOnMountloadOnReloadloadOnResetreloadOnLoadresetOnLoad
Profile query✔️✔️✔️
Login mutation✔️
Logout mutation✔️
Change password mutation
Change name mutation✔️
Like a post mutation✔️

constant GraphQLContext

React context object for a GraphQL instance.

Type: object

PropertyTypeDescription
ProviderFunctionReact context provider component.
ConsumerFunctionReact context consumer component.
See
Examples

A button component that resets the GraphQL cache.

import React from 'react'
import { GraphQLContext } from 'graphql-react'

const ResetCacheButton = () => {
  const graphql = React.useContext(GraphQLContext)
  return <button onClick={graphql.reset}>Reset cache</button>
}

type GraphQLCache

A GraphQL cache map of GraphQL operation results.

Type: object<GraphQLCacheKeyGraphQLCacheValue>

See

type GraphQLCacheKey

A GraphQL cache key, derived from a hash of the fetch options of the GraphQL operation that populated the value.

Type: string


type GraphQLCacheValue

JSON serializable GraphQL operation result that includes errors and data.

Type: object

PropertyTypeDescription
fetchErrorstring?fetch error message.
httpErrorHttpError?fetch response HTTP error.
parseErrorstring?Parse error message.
graphQLErrorsArray<object>?GraphQL response errors.
dataobject?GraphQL response data.

type GraphQLFetchOptions

GraphQL API URL and polyfillable fetch options. The url property gets extracted and the rest are used as fetch options.

Type: object

PropertyTypeDescription
urlstringGraphQL API URL.
bodystring | FormDataHTTP request body.
headersobjectHTTP request headers.
credentialsstring?Authentication credentials mode.
See

type GraphQLFetchOptionsOverride

Overrides default GraphQL fetch options. Mutate the provided options object; there is no need to return it.

Type: Function

ParameterTypeDescription
optionsGraphQLFetchOptionsGraphQL fetch options tailored to the GraphQL operation, e.g. if there are files to upload options.body will be a FormData instance conforming to the GraphQL multipart request spec.
See
Examples

Setting GraphQL fetch options for an imaginary API.

options => {
  options.url = 'https://api.example.com/graphql'
  options.credentials = 'include'
}

type GraphQLOperation

A GraphQL operation. Additional properties may be used; all are sent to the GraphQL server.

Type: object

PropertyTypeDescription
querystringGraphQL queries/mutations.
variablesobjectVariables used in the query.
See

type GraphQLOperationLoading

A loading GraphQL operation.

Type: object

PropertyTypeDescription
cacheKeyGraphQLCacheKeyGraphQL cache key.
cacheValueGraphQLCacheValue?GraphQL cache value from the last identical query.
cacheValuePromisePromise<GraphQLCacheValue>Resolves the loaded GraphQL cache value.
See

type GraphQLOperationStatus

The status of a GraphQL operation.

Type: object

PropertyTypeDescription
loadFunctionLoads the GraphQL operation on demand, updating the GraphQL cache.
loadingbooleanIs the GraphQL operation loading.
cacheKeyGraphQLCacheKeyGraphQL cache key.
cacheValueGraphQLCacheValueGraphQL cache value.
See

type HttpError

fetch HTTP error.

Type: object

PropertyTypeDescription
statusnumberHTTP status code.
statusTextstringHTTP status text.

type ReactNode

A React virtual DOM node; anything that can be rendered.

Type: undefined | null | boolean | number | string | React.Element | Array<ReactNode>

Keywords

FAQs

Package last updated on 16 Jul 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc