React Relay

20.1.1 · active · verified Sun Apr 19

React Relay is a JavaScript framework developed by Meta for building highly performant and data-driven React applications using GraphQL. It provides a robust client-side data store, automatic query batching, optimistic updates, and a compile-time artifact generation process that ensures type safety and optimized network requests. Currently at version 20.1.1, Relay maintains an active development pace with frequent patch and minor releases, alongside major releases introducing significant features and breaking changes on a regular cadence. Key differentiators include its tight integration with GraphQL at a compiler level, enabling advanced optimizations like persisted queries and fragment colocation, and its comprehensive approach to client-side data management, including client-side state through Relay Resolvers. Its compiler tooling is a core component, transforming GraphQL declarations into optimized, type-safe code.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic Relay Environment, defining a GraphQL query, and using `useLazyLoadQuery` within a React component to fetch and display data, including Suspense for loading states. It connects to a public Star Wars API.

import React from 'react';
import { 
  RelayEnvironmentProvider, 
  loadQuery, 
  useLazyLoadQuery, 
  graphql 
} from 'react-relay';
import { 
  Environment, 
  Network, 
  RecordSource, 
  Store 
} from 'relay-runtime';

// 1. Define a Network Layer
const fetchGraphQL = async (text, variables) => {
  const response = await fetch('https://swapi-graphql.netlify.app/.netlify/functions/index', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: text, variables }),
  });
  return await response.json();
};

const network = Network.create(fetchGraphQL);

// 2. Create a Relay Store
const store = new Store(new RecordSource());

// 3. Create a Relay Environment
const environment = new Environment({
  network,
  store,
});

// 4. Define a Query
const AppQuery = graphql`
  query AppQuery {
    allFilms {
      films {
        title
        releaseDate
      }
    }
  }
`;

// 5. Pre-load the query for suspense (optional, but good practice)
const preloadedQuery = loadQuery(environment, AppQuery, {});

function FilmList() {
  const data = useLazyLoadQuery(AppQuery, {}, { fetchPolicy: 'store-or-network' });

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

export default function AppRoot() {
  return (
    <RelayEnvironmentProvider environment={environment}>
      <React.Suspense fallback={<div>Loading...</div>}>
        <FilmList />
      </React.Suspense>
    </RelayEnvironmentProvider>
  );
}

view raw JSON →