
graphql-react

A lightweight GraphQL client for React; the first Relay and Apollo alternative with server side rendering.
Easy 🔥
- Add 1 dependency to get started with GraphQL in a React project.
- No Webpack or Babel setup.
- Simple components, no decorators.
- Query components fetch on mount and when props change. While loading, cache from the last identical request is available to display.
- Automatically fresh cache, even after mutations.
- Use file input values as mutation arguments to upload files; compatible with a variety of servers.
- Template literal queries; no need for
gql
. - Query multiple GraphQL APIs.
Smart 💡
- Adds only a few KB to a typical min+gzip bundle.
- Native ESM in Node.js via
.mjs
. - Package
module
entry for tree shaking bundlers. - Server side rendering for crawlable pages and a better UX.
- Components use the React v16.3 context API.
- All fetch options overridable per request.
- GraphQL request fetch options hash based cache:
- No data denormalization or need to query
id
fields. - No tampering with queries or
__typename
insertion. - Errors are cached and can be server side rendered.
- Query multiple GraphQL APIs without stitching data.
Setup
Install with npm:
npm install graphql-react
Create and provide a GraphQL client:
import { GraphQL, Provider } from 'graphql-react'
const graphql = new GraphQL()
const Page = () => (
<Provider value={graphql}>Use Consumer or Query components…</Provider>
)
Example
See the example GraphQL API and Next.js web app, deployed at graphql-react.now.sh.
Support
Consider polyfilling:
API
Table of Contents
GraphQL
A lightweight GraphQL client that caches requests.
Parameters
options
Object Options. (optional, default {}
)
options.cache
Object Cache to import; usually from a server side render. (optional, default {}
)
Examples
import { GraphQL } from 'graphql-react'
const graphql = new GraphQL()
cache
GraphQL request cache map, keyed by fetch options hashes.
Type: Object<string, RequestCache>
Examples
Export cache as JSON.
const exportedCache = JSON.stringify(graphql.cache)
query
Queries a GraphQL server.
Parameters
Returns ActiveQuery Loading query details.
reset
Resets the GraphQL cache. Useful when a user logs out.
Parameters
exceptFetchOptionsHash
string? A fetch options hash to exempt a request from cache deletion. Useful for resetting cache after a mutation, preserving the mutation cache.
Examples
graphql.reset()
Provider
A React component provides a GraphQL instance in context for nested Consumer components to use.
Parameters
Examples
import { GraphQL, Provider } from 'graphql-react'
const graphql = new GraphQL()
const Page = () => (
<Provider value={graphql}>Use Consumer or Query components…</Provider>
)
Returns ReactElement React virtual DOM element.
Consumer
A React component that gets the GraphQL instance from context.
Parameters
Examples
A button component that resets the GraphQL cache.
import { Consumer } from 'graphql-react'
const ResetCacheButton = () => (
<Consumer>
{graphql => <button onClick={graphql.reset}>Reset cache</button>}
</Consumer>
)
Returns ReactElement React virtual DOM element.
ConsumerRender
Renders a GraphQL consumer.
Type: Function
Parameters
Examples
A button that resets the GraphQL cache.
graphql => <button onClick={graphql.reset}>Reset cache</button>
Returns ReactElement React virtual DOM element.
Query
A React component to manage a GraphQL query or mutation.
Parameters
props
Object Component props.
props.variables
Object? GraphQL query variables.props.query
string GraphQL query.props.fetchOptionsOverride
FetchOptionsOverride? Overrides default GraphQL request fetch options.props.loadOnMount
boolean Should the query load when the component mounts. (optional, default false
)props.loadOnReset
boolean Should the query load when the GraphQL cache is reset. (optional, default false
)props.resetOnLoad
boolean Should the GraphQL cache reset when the query loads. (optional, default false
)props.children
QueryRender Renders the query status.
Examples
A query to display a user profile.
import { Query } from 'graphql-react'
const Profile = ({ userId }) => (
<Query
loadOnMount
loadOnReset
fetchOptionsOverride={options => {
options.url = 'https://api.example.com/graphql'
}}
variables={{ userId }}
query={`
query user($userId: ID!) {
user(userId: $id) {
name
}
}
`}
>
{({
load,
loading,
fetchError,
httpError,
parseError,
graphQLErrors,
data
}) => (
<article>
<button onClick={load}>Reload</button>
{loading && <span>Loading…</span>}
{(fetchError || httpError || parseError || graphQLErrors) && (
<strong>Error!</strong>
)}
{data && <h1>{data.user.name}</h1>}
</article>
)}
</Query>
)
A mutation to clap an article.
import { Query } from 'graphql-react'
const ClapArticleButton = ({ articleId }) => (
<Query
resetOnLoad
fetchOptionsOverride={options => {
options.url = 'https://api.example.com/graphql'
}}
variables={{ articleId }}
query={`
mutation clapArticle($articleId: ID!) {
clapArticle(articleId: $id) {
clapCount
}
}
`}
>
{({
load,
loading,
fetchError,
httpError,
parseError,
graphQLErrors,
data
}) => (
<aside>
<button onClick={load} disabled={loading}>
Clap
</button>
{(fetchError || httpError || parseError || graphQLErrors) && (
<strong>Error!</strong>
)}
{data && <p>Clapped {data.clapArticle.clapCount} times.</p>}
</aside>
)}
</Query>
)
Returns ReactElement React virtual DOM element.
QueryRender
Renders the status of a query or mutation.
Type: Function
Parameters
load
Function Loads the query on demand, updating cache.loading
boolean Is the query loading.fetchError
string? Fetch error message.httpError
HTTPError? Fetch response HTTP error.parseError
string? Parse error message.graphQLErrors
Object? GraphQL response errors.data
Object? GraphQL response data.
Examples
;({
load,
loading,
fetchError,
httpError,
parseError,
graphQLErrors,
data
}) => (
<aside>
<button onClick={load}>Reload</button>
{loading && <span>Loading…</span>}
{(fetchError || httpError || parseError || graphQLErrors) && (
<strong>Error!</strong>
)}
{data && <h1>{data.user.name}</h1>}
</aside>
)
Returns ReactElement React virtual DOM element.
preload
Recursively preloads Query components that have the loadOnMount
prop in a React element tree. Useful for server side rendering (SSR) or to preload components for a better user experience when they mount.
Parameters
element
ReactElement A React virtual DOM element.
Examples
An async SSR function that returns a HTML string and cache JSON for client hydration.
import { GraphQL, preload, Provider } from 'graphql-react'
import { renderToString } from 'react-dom/server'
import { App } from './components'
const graphql = new GraphQL()
const page = (
<Provider value={graphql}>
<App />
</Provider>
)
export async function ssr() {
await preload(page)
return {
cache: JSON.stringify(graphql.cache),
html: renderToString(page)
}
}
Returns Promise Resolves once loading is done and cache is ready to be exported from the GraphQL instance. Cache can be imported when constructing new GraphQL instances.
ActiveQuery
Loading query details.
Type: Object
Properties
FetchOptions
Fetch options for a GraphQL request. See polyfillable fetch options.
Type: Object
Properties
url
string A GraphQL API URL.body
(string | FormData) HTTP request body.headers
Object HTTP request headers.credentials
string? Authentication credentials mode.
FetchOptionsOverride
Overrides default GraphQL request fetch options. Modify the provided options object without a return.
Type: Function
Parameters
fetchOptions
FetchOptions Default GraphQL request fetch options.operation
Operation? A GraphQL operation object.
Examples
options => {
options.url = 'https://api.example.com/graphql'
options.credentials = 'include'
}
HTTPError
Fetch HTTP error.
Type: Object
Properties
status
number HTTP status code.statusText
string HTTP status text.
Operation
A GraphQL operation object. Additional properties may be used; all are sent to the GraphQL server.
Type: Object
Properties
query
string GraphQL queries or mutations.variables
Object Variables used by the query.
RequestCache
JSON serializable result of a GraphQL request (including all errors and data) suitable for caching.
Type: Object
Properties
fetchError
string? Fetch error message.httpError
HTTPError? Fetch response HTTP error.parseError
string? Parse error message.graphQLErrors
Object? GraphQL response errors.data
Object? GraphQL response data.
RequestCachePromise
A promise for a loading query that resolves the request cache.
Type: Promise<RequestCache>