What is relay-runtime?
The relay-runtime package is a part of the Relay framework, which is a JavaScript framework for building data-driven React applications with GraphQL. It provides a runtime environment for managing and executing GraphQL queries, caching query results, and updating the UI. It is designed to be efficient, fast, and scalable.
What are relay-runtime's main functionalities?
Network Layer
The network layer is responsible for defining how Relay communicates with the GraphQL server. It uses a fetch function to send queries and mutations and process the responses.
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
// Define a function that fetches the results of an operation (query/mutation/etc)
// and returns its results as a Promise:
function fetchQuery(operation, variables) {
return fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: operation.text, // GraphQL text from input
variables,
}),
}).then(response => {
return response.json();
});
}
// Create a network layer from the fetch function
const network = Network.create(fetchQuery);
// Create a record source to store the data
const store = new Store(new RecordSource());
// Create an environment using the configured network and store
const environment = new Environment({
network,
store,
});
Store and RecordSource
The store is where Relay keeps its cache of GraphQL data. RecordSource is the low-level storage API used by Store to manage records. Together, they enable the caching and management of query results.
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
const store = new Store(new RecordSource());
const environment = new Environment({
network: Network.create(fetchQuery),
store,
});
Garbage Collection
Relay's store provides garbage collection capabilities to clean up data that is no longer referenced by any active queries, which helps in managing memory usage.
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
const store = new Store(new RecordSource());
store.gc();
const environment = new Environment({
network: Network.create(fetchQuery),
store,
});
Optimistic Updates
Optimistic updates allow Relay to simulate the results of a mutation on the client side before the server responds, providing a snappier user experience.
import { commitMutation, graphql } from 'react-relay';
import { ConnectionHandler } from 'relay-runtime';
const mutation = graphql`
mutation CommentMutation($input: CommentInput!) {
comment(input: $input) {
commentEdge {
node {
id
text
}
}
}
}
`;
const optimisticResponse = {
comment: {
commentEdge: {
node: {
id: 'temp-id',
text: 'This is a temporary comment',
},
},
},
};
commitMutation(
environment,
{
mutation,
variables: { input: { text: 'Hello world!' } },
optimisticResponse,
}
);
Other packages similar to relay-runtime
apollo-client
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It is similar to relay-runtime in that it provides features for executing GraphQL operations, caching results, and updating the UI. Apollo Client is known for its flexibility and ease of integration with various view layers, not just React.
urql
urql is a lightweight and extensible GraphQL client for React, designed to be highly customizable and easy to understand. It offers similar functionalities to relay-runtime, such as executing GraphQL queries and mutations, caching, and optimistic updates. urql differentiates itself with a focus on simplicity and a smaller bundle size.
graphql-request
graphql-request is a minimal GraphQL client for making HTTP requests. It is much simpler than relay-runtime and is suitable for small applications or simple use cases where the overhead of a full-featured GraphQL client is not necessary. It does not provide a caching layer or advanced features like subscriptions and optimistic updates.
Relay Runtime
A set of Relay APIs responsible for data fetching, reading and normalization of
the GraphQL data.
Example:
import type {FetchFunction} from 'relay-runtime';
const {
Environment,
Network,
Observable,
RecordSource,
Store,
fetchQuery,
graphql,
} = require('relay-runtime');
const fetchFn: FetchFunction = function (request, variables) {
return new Observable.create(source => {
fetch('/my-graphql-api', {
method: 'POST',
body: JSON.stringify({
text: request.text,
variables,
}),
})
.then(response => response.json())
.then(data => source.next(data));
});
};
const network = Network.create(fetchFn);
const store = new Store(new RecordSource());
const environment = new Environment({
network,
store,
});
fetchQuery(
environment,
graphql`
query AppQuery($id: ID!) {
user(id: $id) {
name
}
}
`,
{id: 'my-node-id'},
).subscribe({
error: error => {
console.error(error);
},
next: data => {
console.log(data);
},
});
For complete API reference, visit https://relay.dev/.