urql — Lightweight GraphQL Client
You are an expert in urql, the highly customizable and lightweight GraphQL client for React, Vue, Svelte, and vanilla JavaScript. You help developers fetch GraphQL data with minimal bundle size, document caching, normalized caching via Graphcache, exchanges (middleware pipeline), subscriptions, and offline support — providing a leaner alternative to Apollo Client with better extensibility.
Core Capabilities
Setup and Queries
import { Client, Provider, cacheExchange, fetchExchange, gql, useQuery, useMutation } from "urql";
const client = new Client({
url: "https://api.example.com/graphql",
exchanges: [cacheExchange, fetchExchange],
fetchOptions: () => ({
headers: { Authorization: `Bearer ${getToken()}` },
}),
});
function App() {
return <Provider value={client}><Dashboard /></Provider>;
}
const POSTS_QUERY = gql`
query Posts($limit: Int!) {
posts(limit: $limit) { id title author { name } createdAt }
}
`;
function PostList() {
const [result, reexecute] = useQuery({
query: POSTS_QUERY,
variables: { limit: 10 },
});
const { data, fetching, error } = result;
if (fetching) return <Spinner />;
if (error) return <Error message={error.message} />;
return (
<div>
{data.posts.map(p => <PostCard key={p.id} post={p} />)}
<button => reexecute({ requestPolicy: "network-only" })}>Refresh</button>
</div>
);
}
Mutations
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) { id title createdAt }
}
`;
function CreatePostForm() {
const [result, createPost] = useMutation(CREATE_POST);
const handleSubmit = (data: any) => {
createPost({ input: data }).then(result => {
if (result.error) console.error(result.error);
});
};
return <Form loading={result.fetching} />;
}
Graphcache (Normalized Cache)
import { cacheExchange } from "@urql/exchange-graphcache";
const cache = cacheExchange({
keys: { Post: (data) => data.id as string },
resolvers: {
Query: {
post: (_, args) => ({ __typename: "Post", id: args.id }),
},
},
updates: {
Mutation: {
createPost(result, _args, cache) {
cache.updateQuery({ query: POSTS_QUERY, variables: { limit: 10 } }, (data) => {
if (data) data.posts.unshift(result.createPost);
return data;
});
},
},
},
});
Installation
npm install urql graphql
npm install @urql/exchange-graphcache # Optional normalized cache
Best Practices
- Document cache — Default cache deduplicates by query+variables; sufficient for most apps
- Graphcache for complex — Use normalized cache only when you need cache updates across queries
- Exchanges — urql's middleware pipeline; add auth, retry, persist, logging as composable exchanges
- Request policies — Use
cache-first (default), network-only for refresh, cache-and-network for stale-while-revalidate
- Bundle size — urql core is ~5KB gzipped (vs Apollo ~30KB); ideal for performance-sensitive apps
- SSR support — Use
ssrExchange for server-side rendering; hydrates cache on client
- Subscriptions — Add
subscriptionExchange for WebSocket/SSE subscriptions; plug and play
- Framework agnostic — Works with React, Vue, Svelte, and vanilla JS; same core, different bindings
1---2name: urql3description: >-4 You are an expert in urql, the highly customizable and lightweight GraphQL5 client for React, Vue, Svelte, and vanilla JavaScript. You help developers6 fetch GraphQL data with minimal bundle size, document caching, normalized7 caching via Graphcache, exchanges (middleware pipeline), subscriptions, and8 offline support — providing a leaner alternative to Apollo Client with9 better extensibility.10license: Apache-2.011compatibility: ''12metadata:13 source: https://skillmd.com/skills/eliferjunior/urql14 author: terminal-skills15 version: 1.0.016 category: Frontend Development17 tags:18 - graphql19 - react20 - client21 - lightweight22 - cache23 - exchange24 - typescript25---2627# urql — Lightweight GraphQL Client2829You are an expert in urql, the highly customizable and lightweight GraphQL client for React, Vue, Svelte, and vanilla JavaScript. You help developers fetch GraphQL data with minimal bundle size, document caching, normalized caching via Graphcache, exchanges (middleware pipeline), subscriptions, and offline support — providing a leaner alternative to Apollo Client with better extensibility.3031## Core Capabilities3233### Setup and Queries3435```tsx36import { Client, Provider, cacheExchange, fetchExchange, gql, useQuery, useMutation } from "urql";3738const client = new Client({39 url: "https://api.example.com/graphql",40 exchanges: [cacheExchange, fetchExchange],41 fetchOptions: () => ({42 headers: { Authorization: `Bearer ${getToken()}` },43 }),44});4546function App() {47 return <Provider value={client}><Dashboard /></Provider>;48}4950const POSTS_QUERY = gql`51 query Posts($limit: Int!) {52 posts(limit: $limit) { id title author { name } createdAt }53 }54`;5556function PostList() {57 const [result, reexecute] = useQuery({58 query: POSTS_QUERY,59 variables: { limit: 10 },60 });6162 const { data, fetching, error } = result;63 if (fetching) return <Spinner />;64 if (error) return <Error message={error.message} />;65 return (66 <div>67 {data.posts.map(p => <PostCard key={p.id} post={p} />)}68 <button onClick={() => reexecute({ requestPolicy: "network-only" })}>Refresh</button>69 </div>70 );71}72```7374### Mutations7576```tsx77const CREATE_POST = gql`78 mutation CreatePost($input: CreatePostInput!) {79 createPost(input: $input) { id title createdAt }80 }81`;8283function CreatePostForm() {84 const [result, createPost] = useMutation(CREATE_POST);8586 const handleSubmit = (data: any) => {87 createPost({ input: data }).then(result => {88 if (result.error) console.error(result.error);89 });90 };9192 return <Form onSubmit={handleSubmit} loading={result.fetching} />;93}94```9596### Graphcache (Normalized Cache)9798```typescript99import { cacheExchange } from "@urql/exchange-graphcache";100101const cache = cacheExchange({102 keys: { Post: (data) => data.id as string },103 resolvers: {104 Query: {105 post: (_, args) => ({ __typename: "Post", id: args.id }),106 },107 },108 updates: {109 Mutation: {110 createPost(result, _args, cache) {111 cache.updateQuery({ query: POSTS_QUERY, variables: { limit: 10 } }, (data) => {112 if (data) data.posts.unshift(result.createPost);113 return data;114 });115 },116 },117 },118});119```120121## Installation122123```bash124npm install urql graphql125npm install @urql/exchange-graphcache # Optional normalized cache126```127128## Best Practices1291301. **Document cache** — Default cache deduplicates by query+variables; sufficient for most apps1312. **Graphcache for complex** — Use normalized cache only when you need cache updates across queries1323. **Exchanges** — urql's middleware pipeline; add auth, retry, persist, logging as composable exchanges1334. **Request policies** — Use `cache-first` (default), `network-only` for refresh, `cache-and-network` for stale-while-revalidate1345. **Bundle size** — urql core is ~5KB gzipped (vs Apollo ~30KB); ideal for performance-sensitive apps1356. **SSR support** — Use `ssrExchange` for server-side rendering; hydrates cache on client1367. **Subscriptions** — Add `subscriptionExchange` for WebSocket/SSE subscriptions; plug and play1378. **Framework agnostic** — Works with React, Vue, Svelte, and vanilla JS; same core, different bindings