urql GraphQL Client for React

5.0.2 · active · verified Tue Apr 21

urql is a lightweight and highly customizable GraphQL client primarily designed for React applications, though it offers integrations for other frameworks like Vue and Svelte via separate packages. It is currently at version 5.0.2 and maintains an active development cycle with frequent patch and minor releases across its extensive ecosystem of exchanges and framework integrations. Its core differentiator is a pluggable 'exchanges' architecture, which allows developers to swap out or add functionalities like caching, authentication, request batching, and subscriptions, making it incredibly adaptable to various application requirements. Unlike some other clients, urql's core remains minimal, pushing advanced features into these composable exchanges, providing fine-grained control and reducing bundle size when not all features are needed. It ships with full TypeScript support.

Common errors

Warnings

Install

Imports

Quickstart

This snippet demonstrates how to set up `urql` with a React application, create a GraphQL client with essential exchanges (`cacheExchange`, `fetchExchange`), and fetch data using the `useQuery` hook, then render the results within a component.

import React from 'react';
import { createRoot } from 'react-dom/client';
import { createClient, Provider, cacheExchange, fetchExchange, useQuery } from 'urql';

// 1. Create your urql client
const client = createClient({
  url: 'https://swapi-graphql.netlify.app/.netlify/functions/index', // Example public GraphQL API
  exchanges: [cacheExchange, fetchExchange], // Define the exchanges to use (e.g., caching, fetching)
});

// 2. Define a React component that uses the useQuery hook
const StarWarsFilms = () => {
  const [result] = useQuery({
    query: `
      query AllFilms {
        allFilms {
          films {
            title
            director
            releaseDate
          }
        }
      }
    `,
  });

  const { data, fetching, error } = result;

  if (fetching) return <p>Loading films...</p>;
  if (error) return <p>Oh no... {error.message}</p>;

  return (
    <div>
      <h1>Star Wars Films</h1>
      <ul>
        {data.allFilms.films.map((film) => (
          <li key={film.title}>
            <strong>{film.title}</strong> by {film.director} (Released: {film.releaseDate})
          </li>
        ))}
      </ul>
    </div>
  );
};

// 3. Wrap your root component with the Provider
const App = () => (
  <Provider value={client}>
    <StarWarsFilms />
  </Provider>
);

// 4. Render your application
const container = document.getElementById('root');
if (container) {
  const root = createRoot(container);
  root.render(<App />);
} else {
  console.error("Root element not found");
}

view raw JSON →