Urql – A highly customizable and versatile GraphQL client for React

From the folks at FormidableLabs:

urql is a GraphQL client that exposes a set of React components and hooks. It’s built to be highly customisable and versatile so you can take it from getting started with your first GraphQL project all the way to building complex apps and experimenting with GraphQL clients.

// App.js
import { Provider, createClient } from 'urql';

const client = createClient({
  url: 'http://localhost:4000/graphql',
});

const App = () => (
  <Provider value={client}>
    <TodoList />
  </Provider>;
);
// TodoList.js
import React from 'react';
import { Query } from 'urql';

const getTodos = `
  query GetTodos($limit: Int!) {
    todos(limit: $limit) {
      id
      text
      isDone
    }
  }
`;

const TodoList = ({ limit = 10 }) => (
  <Query query={getTodos} variables={{ limit }}>
    {({ fetching, data, error, extensions }) => {
      if (fetching) {
        return 'Loading...';
      } else if (error) {
        return 'Oh no!';
      }

      return (
        <ul>
          {data.todos.map(({ id, text }) => (
            <li key={id}>{text}</li>
          ))}
        </ul>
      );
    }}
  </Query>;
);

I know I’ve posted about this one before, but a lot has changed since then. Biggest change is that Urql now supports React Hooks. The TodoList example from above would then become:

const TodoList = ({ limit = 10 }) => {
  const [res] = useQuery({
    query: getTodos,
    variables: { limit },
  });

  if (res.fetching) {
    return 'Loading...';
  } else if (res.error) {
    return 'Oh no!';
  }

  return (
    <ul>
      {res.data.todos.map(({ id, text }) => (
        <li key={id}>{text}</li>
      ))}
    </ul>
  );
};

Over at Egghead you can watch some lessons how to use urql with Hooks:

You will learn how to set up an Urql Provider component so that all of your React components have access to Urql. Then you will learn how to use 3 of Urql’s React Hooks:

  • useQuery
  • useMutation
  • useSubscription

There’s also a few good examples listed in GraphQL and Urql by Example on dev.to

Installation per npm/Yarn:

yarn add urql graphql

Urql →
Urql Source (GitHub)
Egghead: Introduction to Urql →

💁‍♂️ The “older” Apollo GraphQL Client also received hooks support recently …

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.