Convert Figma logo to code with AI

facebook logorelay

Relay is a JavaScript framework for building data-driven React applications.

18,357
1,815
18,357
679

Top Related Projects

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.

5,803

Minimal GraphQL client

A reference implementation of GraphQL for JavaScript

The Fullstack Tutorial for GraphQL

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

3,395

Code-First, Type-Safe, GraphQL Schema Construction

Quick Overview

Relay is a JavaScript framework for building data-driven React applications. It provides a declarative approach to fetching and managing data, allowing developers to describe their data requirements alongside their UI components. Relay integrates tightly with GraphQL, optimizing data fetching and caching.

Pros

  • Efficient data fetching: Relay colocates data requirements with components, reducing over-fetching and under-fetching of data.
  • Automatic caching and updates: Relay manages a client-side cache, automatically updating the UI when data changes.
  • Type safety: When used with TypeScript, Relay provides strong type checking for GraphQL queries and mutations.
  • Performance optimizations: Relay includes features like query batching and incremental loading to improve application performance.

Cons

  • Steep learning curve: Relay has a complex architecture and requires understanding of both React and GraphQL concepts.
  • Boilerplate code: Setting up Relay can require more initial configuration compared to simpler data fetching solutions.
  • Limited flexibility: Relay's opinionated approach may not suit all project structures or requirements.
  • GraphQL dependency: Relay is tightly coupled with GraphQL, which may not be suitable for projects using REST APIs or other data sources.

Code Examples

  1. Defining a Relay fragment:
import { graphql, useFragment } from 'react-relay';

const UserFragment = graphql`
  fragment UserComponent_user on User {
    id
    name
    email
  }
`;

function UserComponent(props) {
  const user = useFragment(UserFragment, props.user);
  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
}
  1. Querying data with Relay:
import { graphql, useLazyLoadQuery } from 'react-relay';

const UserQuery = graphql`
  query UserQuery($id: ID!) {
    user(id: $id) {
      ...UserComponent_user
    }
  }
`;

function UserContainer({ userId }) {
  const data = useLazyLoadQuery(UserQuery, { id: userId });
  return <UserComponent user={data.user} />;
}
  1. Performing a mutation:
import { graphql, useMutation } from 'react-relay';

const UpdateUserMutation = graphql`
  mutation UpdateUserMutation($input: UpdateUserInput!) {
    updateUser(input: $input) {
      user {
        id
        name
      }
    }
  }
`;

function UpdateUserButton({ userId }) {
  const [commit, isInFlight] = useMutation(UpdateUserMutation);
  
  const handleClick = () => {
    commit({
      variables: {
        input: { id: userId, name: 'New Name' },
      },
    });
  };

  return <button onClick={handleClick} disabled={isInFlight}>Update User</button>;
}

Getting Started

To start using Relay in your React project:

  1. Install Relay and its dependencies:

    npm install relay-runtime react-relay
    npm install --dev relay-compiler babel-plugin-relay
    
  2. Set up Relay compiler in your package.json:

    {
      "scripts": {
        "relay": "relay-compiler"
      }
    }
    
  3. Configure Babel plugin in .babelrc:

    {
      "plugins": ["relay"]
    }
    
  4. Create a Relay environment:

    import { Environment, Network, RecordSource, Store } from 'relay-runtime';
    
    const fetchQuery = async (operation, variables) => {
      const response = await fetch('/graphql', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: operation.text, variables }),
      });
      return response.json();
    };
    
    const environment = new Environment({
      network: Network.create(fetchQuery),
      store: new Store(new Recor
    

Competitor Comparisons

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.

Pros of Apollo Client

  • Easier learning curve and more flexible integration
  • Better documentation and community support
  • Works with various backends, not limited to GraphQL

Cons of Apollo Client

  • Less optimized for performance in large-scale applications
  • Lacks some advanced features like automatic query batching

Code Comparison

Apollo Client:

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache()
});

Relay:

import { Environment, Network, RecordSource, Store } from 'relay-runtime';

const network = Network.create(fetchQuery);
const environment = new Environment({
  network,
  store: new Store(new RecordSource()),
});

Key Differences

  • Apollo Client is more flexible and easier to set up, while Relay is more opinionated and requires more configuration.
  • Relay has better performance optimizations for large-scale applications, particularly with data normalization and query colocation.
  • Apollo Client has a larger ecosystem and works with various backend technologies, whereas Relay is primarily designed for GraphQL.
  • Relay enforces stricter conventions, which can lead to more maintainable code in large projects but may feel restrictive for smaller applications.

Both libraries are powerful tools for managing GraphQL data in React applications, with Apollo Client offering more flexibility and ease of use, while Relay provides better performance and structure for complex, large-scale projects.

5,803

Minimal GraphQL client

Pros of Graffle

  • Lightweight and focused on GraphQL schema generation
  • Simpler learning curve for developers new to GraphQL
  • More flexible and customizable for specific use cases

Cons of Graffle

  • Less mature and battle-tested compared to Relay
  • Smaller community and ecosystem support
  • Limited built-in optimizations for complex data fetching scenarios

Code Comparison

Graffle schema definition:

const schema = gql`
  type User {
    id: ID!
    name: String!
  }
`;

Relay schema definition:

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString },
  },
});

Summary

Graffle offers a more lightweight and flexible approach to GraphQL schema generation, making it easier for developers to get started with GraphQL. However, it lacks the maturity and extensive optimizations provided by Relay, which has been battle-tested in large-scale applications. Relay provides a more comprehensive solution for complex data fetching scenarios and benefits from Facebook's extensive ecosystem support. The choice between the two depends on project requirements, team expertise, and scalability needs.

A reference implementation of GraphQL for JavaScript

Pros of GraphQL.js

  • More flexible and can be used with any JavaScript framework or library
  • Provides a reference implementation of the GraphQL specification
  • Easier to integrate into existing projects without a full framework commitment

Cons of GraphQL.js

  • Requires more manual setup and configuration for complex data fetching scenarios
  • Lacks built-in optimizations and performance enhancements for large-scale applications
  • Does not provide out-of-the-box client-side caching mechanisms

Code Comparison

GraphQL.js:

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      hello: {
        type: GraphQLString,
        resolve: () => 'Hello world!'
      }
    }
  })
});

Relay:

const GreetingQuery = graphql`
  query GreetingQuery {
    hello
  }
`;

function Greeting(props) {
  const data = useLazyLoadQuery(GreetingQuery, {});
  return <div>{data.hello}</div>;
}

The GraphQL.js example shows how to define a simple schema, while the Relay example demonstrates how to define and use a query in a React component. Relay provides a more declarative approach with built-in React integration, whereas GraphQL.js offers lower-level control over schema definition and execution.

The Fullstack Tutorial for GraphQL

Pros of How to GraphQL

  • Comprehensive learning resource for GraphQL, covering multiple languages and frameworks
  • Community-driven project with contributions from various experts in the field
  • Regularly updated with new content and tutorials

Cons of How to GraphQL

  • Not a production-ready library or framework like Relay
  • Lacks advanced features and optimizations for large-scale applications
  • May not cover all edge cases and complex scenarios encountered in real-world projects

Code Comparison

How to GraphQL (example query):

query {
  allPersons {
    name
    age
    posts {
      title
    }
  }
}

Relay (example fragment):

const UserFragment = graphql`
  fragment User_user on User {
    id
    name
    profilePicture(size: $size) {
      url
    }
  }
`;

Summary

How to GraphQL is an educational resource focused on teaching GraphQL concepts across various platforms, while Relay is a production-ready GraphQL client for React applications. How to GraphQL offers a broader scope of learning materials, but lacks the advanced features and optimizations provided by Relay for building large-scale applications. The code examples demonstrate the difference in focus, with How to GraphQL showing basic query structure and Relay showcasing its fragment-based approach for efficient data fetching.

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Pros of GraphQL Engine

  • Provides an instant GraphQL API over existing databases
  • Supports real-time subscriptions out of the box
  • Offers a user-friendly admin interface for managing the GraphQL schema

Cons of GraphQL Engine

  • Less flexible for complex client-side data management
  • May require additional setup for custom business logic
  • Limited to PostgreSQL as the primary database

Code Comparison

GraphQL Engine (Hasura):

type Query {
  users: [User!]!
}

type User {
  id: Int!
  name: String!
  email: String!
}

Relay:

const UserFragment = graphql`
  fragment UserFragment on User {
    id
    name
    email
  }
`;

const UsersQuery = graphql`
  query UsersQuery {
    users {
      ...UserFragment
    }
  }
`;

GraphQL Engine focuses on server-side GraphQL API generation, while Relay is a client-side framework for building React applications with GraphQL. GraphQL Engine simplifies backend development by automatically creating APIs from existing databases, whereas Relay optimizes data fetching and state management on the client-side. The code examples show how GraphQL Engine defines types server-side, while Relay uses fragments and queries client-side for efficient data fetching in React components.

3,395

Code-First, Type-Safe, GraphQL Schema Construction

Pros of Nexus

  • More flexible and easier to set up for smaller projects
  • Better TypeScript integration with auto-generated types
  • Simpler API for defining GraphQL schemas

Cons of Nexus

  • Less optimized for large-scale applications
  • Fewer built-in performance optimizations
  • Smaller community and ecosystem compared to Relay

Code Comparison

Nexus schema definition:

const Query = objectType({
  name: 'Query',
  definition(t) {
    t.list.field('users', {
      type: 'User',
      resolve: () => fetchUsers(),
    })
  },
})

Relay schema definition:

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    users: {
      type: new GraphQLList(UserType),
      resolve: () => fetchUsers(),
    },
  },
})

Nexus offers a more concise and type-safe approach to schema definition, while Relay's approach is more verbose but provides more control over the schema structure. Nexus is generally easier for beginners and smaller projects, while Relay excels in large-scale applications with complex data requirements and performance needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Relay · GitHub license npm version

Relay is a JavaScript framework for building data-driven React applications.

  • Declarative: Never again communicate with your data store using an imperative API. Simply declare your data requirements using GraphQL and let Relay figure out how and when to fetch your data.
  • Colocation: Queries live next to the views that rely on them, so you can easily reason about your app. Relay aggregates queries into efficient network requests to fetch only what you need.
  • Mutations: Relay lets you mutate data on the client and server using GraphQL mutations, and offers automatic data consistency, optimistic updates, and error handling.

See how to use Relay in your own project.

Example

The relay-examples repository contains an implementation of TodoMVC. To try it out:

git clone https://github.com/relayjs/relay-examples.git
cd relay-examples/todo
yarn
yarn build
yarn start

Then, just point your browser at http://localhost:3000.

Contribute

We actively welcome pull requests, learn how to contribute.

Users

We have a community-maintained list of people and projects using Relay in production.

License

Relay is MIT licensed.

Thanks

We'd like to thank the contributors that helped make Relay in open source possible.

The open source project relay-hooks allowed the community to experiment with Relay and React Hooks, and was a source of valuable feedback for us. The idea for the useSubscription hook originated in an issue on that repo. Thank you @morrys for driving this project and for playing such an important role in our open source community.

Thank you for helping make this possible!

NPM DownloadsLast 30 Days