graphql-react
A GraphQL client for React using modern context and hooks APIs that’s lightweight (< 4 kB) but powerful; the first Relay and Apollo alternative with server side rendering.
The exports can also be used to custom load, cache and server side render any data, even from non-GraphQL sources.
Installation
First, polyfill any required globals (see Requirements) that are missing in your server and client environments.
Next.js setup
See the next-graphql-react
setup instructions.
Custom React setup
To install with npm, run:
npm install graphql-react
Create a single Cache
instance and use the Provider
component to provide it for your app.
To server side render your app, use the waterfallRender
function from react-waterfall-render
.
Examples
Here is a basic example using the GitHub GraphQL API, with tips commented:
import useAutoLoad from "graphql-react/useAutoLoad.mjs";
import useCacheEntry from "graphql-react/useCacheEntry.mjs";
import useLoadGraphQL from "graphql-react/useLoadGraphQL.mjs";
import useWaterfallLoad from "graphql-react/useWaterfallLoad.mjs";
import React from "react";
const query = `
query ($repoId: ID!) {
repo: node(id: $repoId) {
... on Repository {
stargazers {
totalCount
}
}
}
}
`;
export default function GitHubRepoStars({ repoId }) {
const cacheKey = `GitHubRepoStars-${repoId}`;
const cacheValue = useCacheEntry(cacheKey);
const loadGraphQL = useLoadGraphQL();
const load = React.useCallback(
() =>
loadGraphQL(
cacheKey,
"https://api.github.com/graphql",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`,
},
body: JSON.stringify({
query,
variables: {
repoId,
},
}),
}
),
[cacheKey, loadGraphQL, repoId]
);
useAutoLoad(cacheKey, load);
const isWaterfallLoading = useWaterfallLoad(cacheKey, load);
return isWaterfallLoading
? null
: cacheValue
? cacheValue.errors
?
"Error!"
: cacheValue.data.repo.stargazers.totalCount
:
"Loading…";
}
Requirements
- Node.js:
^12.22.0 || ^14.17.0 || >= 16.0.0
- Browsers:
> 0.5%, not OperaMini all, not IE > 0, not dead
Consider polyfilling:
Exports
These ECMAScript modules are published to npm and exported via the package.json
exports
field: