DEV Community

Cover image for Welcome to Relay Hooks
Lorenzo Di Giacomo
Lorenzo Di Giacomo

Posted on

Welcome to Relay Hooks

Hi everyone, my name is Lorenzo (morrys), today I want to introduce you to relay-hooks, a library that has allowed me to meet valid people and which is also giving me a lot of satisfaction.
The library was born after a simple chat with Sibelius in which I asked why no one had ever implemented relay hooks.
His response was short: DO IT.

In Early May sibelius added me to the relay-tools organization and on the 13th of May 2019 I made the first commit and first official release of the library on npm.

The initial purpose of the library was to provide the ability to use all react-relay HOCs as react hooks and to implement the store-or-network and store-only policies used by the react-relay-offline library to manage offline relay applications.

After Relay's core team shared information about the the initial differences in the issue https://github.com/relay-tools/relay-hooks/issues/5, all the necessary changes were made in order to make relay-hooks as close as possible to their specifications.

current differences with upcoming Relay Hooks in react-relay

  • useLazyLoadQuery: in the official version returns a single data object with the query's data, and nothing else while in relay-hooks returns the same object of the render function of the QueryRenderer HOC
  • useFragment, usePagination, useRefetchable and useMutation not use suspense

what's more in relay-hooks

  • useQuery: it is the same as useLazyLoadQuery but does not use suspense, it allows you to use hooks without having to migrate the application in concurrent mode and its return is the same as the QueryRenderer HOC
    • useRefetch: it is the same as useRefetchable, allows you to migrate the Refetch Container without changing the fragment specifications
    • conditional useQuery & useLazyLoadQuery: added skip: [Optional] If skip is true, the query will be skipped entirely
    • alternative way to create the "render-as-you-fetch" pattern both for concurrent and non-concurrent modes

why use relay-hooks?

It is a stable library and none of its dependencies is experimental and it allows you to immediately use react hooks with relay-runtime and it is designed for easy migration to react-relay hooks.

Relay Hooks is a light library and fully compatible with React Concurrent Mode and React Legacy Mode (i.e. outside of Concurrent Mode). They are also fully compatible with existing Relay APIs.

Photo by Braden Collum on Unsplash

Photo by Braden Collum on Unsplash

Getting started

First, let's install the packages we need:

# NPM Users
npm install --save relay-runtime relay-hooks
npm install --save-dev relay-compiler graphql babel-plugin-relay

# Yarn Users
yarn add relay-runtime relay-hooks
yarn add --dev relay-compiler graphql babel-plugin-relay

1. Configure Relay Compiler

Here you will find the official documentation on how to configure relay compiler

2. Configure Relay Runtime

Here you will find the official documentation on how to configure relay runtime

3. Connect Relay Runtime to React

You connect Relay Runtime to React with the RelayEnvironmentProvider component. The RelayEnvironmentProvider is similar to React's Context.Provider. It wraps your React app and places the client on the context, which enables you to access it from anywhere in your component tree.

RelayEnvironmentProvider

Since queries with useQuery no longer set context, we will expose a new RelayEnvironmentProvider component that takes an environment and sets it in context; variables will no longer be part of context. A RelayEnvironmentProvider should be rendered once at the root of the app, and multiple useQuery's can be rendered under this environment provider.

4. Use Relay as React hooks

useRelayEnvironment

Hook used to access a Relay environment that was set by a RelayEnvironmentProvider:

useQuery

Hook used to fetch a GraphQL query during render for React Legacy Mode (i.e. outside of Concurrent Mode).
useQuery does not take an environment as an argument. Instead, it reads the environment set in the context; this also implies that it does not set any React context. In addition to query (first argument) and variables (second argument), useQuery accepts a third argument options.

Arguments:

fetchPolicy: determine whether it should use data cached in the Relay store and whether to send a network request. The options are:

  • store-or-network (default): Reuse data cached in the store; if the whole query is cached, skip the network request
  • store-and-network: Reuse data cached in the store; always send a network request.
  • network-only: Don't reuse data cached in the store; always send a network request. (This is the default behavior of Relay's existing QueryRenderer.)
  • store-only: Reuse data cached in the store; never send a network request.

fetchKey: [Optional] A fetchKey can be passed to force a refetch of the current query and variables when the component re-renders, even if the variables didn't change, or even if the component isn't remounted (similarly to how passing a different key to a React component will cause it to remount). If the fetchKey is different from the one used in the previous render, the current query and variables will be refetched.

networkCacheConfig: [Optional] Object containing cache config options for the network layer. Note the the network layer may contain an additional query response cache which will reuse network responses for identical queries. If you want to bypass this cache completely, pass {force: true} as the value for this option.

skip: [Optional] If skip is true, the query will be skipped entirely

useLazyLoadQuery

Hook used to fetch a GraphQL query during render for React Concurrent Mode and the arguments are the same as useQuery

useFragment

useFragment allows components to specify their data requirements. A container does not directly fetch data, but instead declares a specification of the data needed for rendering, and then Relay will guarantee that this data is available before rendering occurs.
The hook is automatically subscribed to updates to the fragment data: if the data for this particular User is updated anywhere in the app (e.g. via fetching new data, or mutating existing data), the component will automatically re-render with the latest updated data.

Arguments:

  • fragment: GraphQL fragment specified using a graphql template literal.
  • fragmentReference: The fragment reference is an opaque Relay object that Relay uses to read the data for the fragment from the store; more specifically, it contains information about which particular object instance the data should be read from.
    • The type of the fragment reference can be imported from the generated Flow/Typescript types, from the file .graphql.js, and can be used to declare the type of your Props. The name of the fragment reference type will be: $key. 

Return Value:

  • data: Object that contains data which has been read out from the Relay store; the object matches the shape of specified fragment.

useRefetch

You can use useRefetch when you want to fetch and re-render a fragment with different data and the arguments are the same as useFragment.

Arguments:

They are the same as useFragment.

Return Value:

Tuple containing the following values

  • [0] data: Object that contains data which has been read out from the Relay store; the object matches the shape of specified fragment.
  • [1] refetch: Function used to refetch the fragment with a potentially new set of variables.

useRefetchable

It is the same as useRefetch but a refetch query no longer needs to be specified in this api, since it will be automatically generated by Relay by using a @refetchable fragment.

usePagination

You can use usePagination to render a fragment that uses a @connection and paginate over it.

Arguments:

They are the same as useFragment.

Return Value:

Tuple containing the following values

  • [0] data: Object that contains data which has been read out from the Relay store; the object matches the shape of specified fragment.
  • [1] paginationFunctions: loadMore, hasMore, isLoading, refetchConnection

useMutation

You can use useMutation to execute a mutation in a React component.

Arguments:

  • fragment: GraphQL fragment specified using a graphql template literal
  • commitMutationFn: An optional function with the same signature as commitMutation to call in its stead.

Return Value:

Tuple containing the following values:

  • [0] mutate: The function that will execute the mutation
  • [1] mutationState: loading, data, error

useSubscription

Hook used to subscribe and unsubscribe to a subscription.

5. Render-as-you-fetch

In relay-hooks I have implemented an alternative way to create the "render-as-you-fetch" pattern both for concurrent and non-concurrent modes.

loadQuery (Non-React API)

Arguments:

same as useQuery + environment

Return value:

  • next: ( environment: IEnvironment, gqlQuery: GraphQLTaggedNode, variables?: TOperationType['variables'], options?: QueryOptions, ) => Promise: fetches data. A promise returns to allow the await in case of SSR
  • dispose: () => void: cancel the subscription and dispose of the fetch
  • subscribe: (callback: (value: any) => any) => () => void: used by the usePreloadedQuery
  • getValue: (environment?: IEnvironment) => RenderProps<TOperationType> | Promise<any>: used by the usePreloadedQuery

loadLazyQuery

loadLazyQuery is the same as loadQuery but must be used with React Concurrent Mode

usePreloadedQuery

Hook used to access data fetched by an earlier call to loadQuery or from loadLazyQuery. This implements the Render-as-You-Fetch pattern.

Arguments:

loadQuery | loadLazyQuery return value

Return Value:

same as useQuery

Render-as-you-fetch Examples:


Conclusions:

Relay-hooks are great. They simplify development by improving DX, reducing the bundle size and allowing you to implement the new "render-as-you-fetch" pattern.
Now you have to try them :)

Top comments (0)