Using Fragments
#
Recommended background reading#
Using FragmentsOne of the main things that make Relay so powerful is using GraphQL fragments to co-locate the data-demands of your components with your actual component code. This leads to well-isolated components that are very portable and easy to maintain.
#
A high-level overview of fragmentsFragments are GraphQL snippets that can be reused throughout your GraphQL operations. At it's core, a fragment is a selection of fields on a specific GraphQL type.
Let's examplify through a basic query, first without fragments:
Here's a very basic query that selects a bunch of fields on the logged in User
. Let's look at the same query, but using fragments representing the various components that would display the data:
See the difference? We've split our data demands on me
into fragments responsible for displaying a certain part of the User
, much like we'd do with React components, delegating displaying different parts of the UI to different, specialized components.
If you want to dive deeper into GraphQL fragments you're encouraged to read through the official documentation on fragments in GraphQL.
#
Fragments in RescriptRelayFragments are defined in RescriptRelay by using the %relay()
extension node. Here's an example of a fragment and a component that renders the fragment data:
A note on naming: Due to the rules of Relay, a fragment must be named
<ModuleName><optionally_anything_here>_<identifier>
, where module name here means file name, not ReScript module name. So for a fileUserProfile.res
, all fragments in that file must start withUserProfile
regardless of whether they're defined in nested modules or not. Identifier can be anything, but it's common to name that after the GraphQL type the fragment targets, lowercased. So a fragment inUserProfile.res
that targets theUser
, would commonly be calledUserProfile_user
.
Using VSCode? Our dedicated VSCode extension lets you codegen new fragments (and optionally boilerplate for a component) via the command
> Add fragment
.
Let's break down what's happening here:
- We define a fragment on the GraphQL type
User
through%relay()
. - We define a React component that takes a
user
prop. %relay()
with a fragment defined in it will autogenerate a React hook calleduse
, which takes any object containing a fragment reference for that particular fragment, and returns the data.- Just as with queries,
use
for fragments is integrated with React suspense, meaning thatuse
will suspend if the data's not already there.
#
Fragment references and how Relay transports fragment dataA fragment always has to end up in a query at some point for it to be able to render. This is quite simply because a fragment is a specification of what data is needed, and somebody (I'm looking at you query) needs to take this specification and get the actual data from the server. Let's tie together the sample fragment code from above with the sample code from making queries in order to demonstrate how components with fragments are used with other components, and how the fragment ends up in a query:
Let's break down what has changed:
- In order for us to be able to render
<UserProfileHeader />
in<UserProfile />
, we need to provide it with the data it needs from theUser
type. It defines what data it needs fromUser
via the fragmentUserProfileHeader_user
, so we spread that fragment on aUser
object in our query. This will ensure that the data demands onUser
for<UserProfileHeader />
is fetched in the query. - When we get the data from
Query.use
, the object where we spreadUserProfileHeader_user
will include a fragment reference for that fragment. Fragment references are how Relay carries the data for fragments, and each fragmentuse
hook knows how to take afragmentRefs
prop containing its own fragment reference and use it to get its own data.
Any object (it's actually a ReScript record, but I'll call it object here) where one or more fragments have been spread will have a prop called fragmentRefs
. That prop will contain all fragment references for all fragments spread. Incidentally, this is exactly what the respective fragment's use
hook wants!
- We make sure we actually got a user, and then we take the
userById
object (where we spreadUserProfileHeader_user
), and pass the fragment references to<UserProfileHeader />
viauserById.fragmentReferences
. That component then passes that to the fragmentUserProfileHeader_user
use
hook, which then exchanges it for the actual fragment data.
Phew! That's a lot to break down. It's really not that complicated to use though.
#
Fragments in fragmentsYup, you read that right, you can spread fragments on other fragments. Remember, a fragment at some point must end up in a query to be usable, but it doesn't mean that each fragment must be spread on a query.
Let's expand our example fragment component to use another component <Avatar />
that is responsible for showing a an avatar for a user:
See the difference? Let's break it down:
- We want to render
<Avatar />
, and it needs data fromUser
. So, we spread its data demands on the user type that we're already getting data for. That will create a fragment reference forAvatar_user
on theuser
record we get back fromUserFragment.use
. - We then pass
userData.fragmentRefs
to<Avatar />
.<Avatar />
then uses that to get the data it needs fromUser
.
We don't have to change anything anywhere else. <UserProfile />
, who defines the query and fetches the data, does not need to know anything about this change. It just knows that it needs to get the data for UserProfileHeader_user
- it's not concerned with how that data looks or if it includes more fragments. It just gets the data for UserProfileHeader_user
, passes it along and minds its own business.
This is a core strength of Relay called data masking - no data is available to anyone unless they explicitly ask for it. You can read more about data masking in Relay here.
#
Using fragments outside of React's render phaseYou can also use fragments outside of React's render phase (read: without using hooks). In addition to Fragment.use
, each fragment will autogenerate a function called Fragment.readInline
if your fragment is annotated with @inline
.@inline
tells Relay you'll want to read this fragment outside of React's render phase.
This works the same way as Fragment.use
as in you feed it an object with a fragment reference for that particular fragment. But, when you run the function, you'll get a one-shot snapshot of that fragment data from the store as it is right now.
Great for logging and similar activities. Example:
#
On to the next thingThat's a basic introduction to fragments. There are a few more concepts around fragments that are worth spending some time to grok. However, none of them are specific to using Relay with Reason, so you can read more about them in the Relay documentation below.
Before we move on to the next thing, there's a few things that's worth keeping in mind about fragments:
- Use fragments as much as you can. They are optimized for performance and help promote well contained and isolated components
- A component can use any number of fragments, not just one
- A fragment can use other fragments
- Any object where a fragment has been spread will have a prop called
fragmentRefs
. This contains references for all fragments that have been spread on that object. You pass thatfragmentReferences
prop to the respective fragment'suse
hooks.
With that in mind, Let's jump in to mutations.
#
API Reference%relay()
is expanded to a module containing the following functions:
use
#
SomeFragment.use
is a React hook that takes an object containing a fragment reference for that particular fragment, and returns the fragment data.
use
uses Relay'suseFragment
under the hood, which you can read more about here.
readInline
#
SomeFragment.readInline
is a function that takes an object containing a fragment reference for that particular fragment, and returns the fragment data. Can be used outside of React's render phase.
readInline
uses Relay'sreadInlineData
under the hood.