Welcome to Relay Hooks
Tags: relay, hooks, graphql, react
Published: 2020-08-07 11:50:47

Hi everyone, my name is Lorenzo ([morrys](https://github.com/morrys/)), today I want to introduce you to [relay-hooks](https://www.npmjs.com/package/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](https://github.com/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](https://github.com/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](https://github.com/morrys/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](https://reactjs.org/docs/concurrent-mode-suspense.html#approach-3-render-as-you-fetch-using-suspense)" 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](https://reactjs.org/docs/concurrent-mode-intro.html) and React Legacy Mode (i.e. outside of Concurrent Mode). They are also fully compatible with [existing Relay APIs](https://relay.dev/docs/en/introduction-to-relay).

![Photo by Braden Collum on Unsplash](https://dev-to-uploads.s3.amazonaws.com/i/z3kuyicrv9t87v5w2nd1.jpg)
<figcaption> Photo by Braden Collum on Unsplash </figcaption>
           

---

#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](https://relay.dev/docs/en/experimental/step-by-step#41-configure-relay-compiler)

##2. Configure Relay Runtime
[Here you will find the official documentation on how to configure relay runtime](https://relay.dev/docs/en/experimental/step-by-step#42-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](https://reactjs.org/docs/context.html#contextprovider).  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.


{% gist https://gist.github.com/morrys/ca9fa45129281167e9fd4c2d1775d4b3 %}


##4. Use Relay as React hooks 

###useRelayEnvironment

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


{% gist 
https://gist.github.com/morrys/5a2a11540c57f2e290a79aa124e4885b %}



###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


{% gist https://gist.github.com/morrys/e3ea0c35e87438a8657eb0299a6a80f6 %}


###useLazyLoadQuery

Hook used to fetch a GraphQL query during render for [React Concurrent Mode](https://reactjs.org/docs/concurrent-mode-intro.html) and the arguments are the same as useQuery

{% gist https://gist.github.com/morrys/32a0ea2bc10084db0114b9bd2d0894b2 %}



###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 <fragment_name>.graphql.js, and can be used to declare the type of your Props. The name of the fragment reference type will be: <fragment_name>$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.

{% gist https://gist.github.com/morrys/b057cc9b553de6fa6c583423c714da4b  %}


###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.

{% gist https://gist.github.com/morrys/d220b84de8fd711c8f542f2c446ab3ad  %}



###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.

{% gist https://gist.github.com/morrys/96c3ec5bfeda618048b4944b64931d97  %}



###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

{% gist https://gist.github.com/morrys/3ca1424c9cea8c0205a29978d0323a67  %}



###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

{% gist https://gist.github.com/morrys/4d285e67d89f4e59e1639f0e75734d01  %}



###useSubscription

Hook used to subscribe and unsubscribe to a subscription.

{% gist https://gist.github.com/morrys/911608e497a0903fc93e31c4983e9a3d  %}


##5. Render-as-you-fetch

In relay-hooks I have implemented an alternative way to create the "[render-as-you-fetch](https://reactjs.org/docs/concurrent-mode-suspense.html#approach-3-render-as-you-fetch-using-suspense)" 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<void>:  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


{% gist https://gist.github.com/morrys/ebe756e35ae81d68ff4f9ae791b366dc  %}



###loadLazyQuery

loadLazyQuery is the same as loadQuery but must be used with [React Concurrent Mode](https://reactjs.org/docs/concurrent-mode-intro.html)

###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

{% gist https://gist.github.com/morrys/625a10d2c98bc4ff6f5f005b153db077  %}




###Render-as-you-fetch Examples:

* [Complete example with nextjs, SSR in React Concurrent](https://github.com/relay-tools/relay-hooks/tree/master/examples/suspense/nextjs-ssr-preload)
* [Complete example with nextjs, SSR in React Legacy](https://github.com/relay-tools/relay-hooks/tree/master/examples/relay-hook-example/nextjs-ssr-preload)


---

#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 :)