GraphQL Fragments: The Key to Soundness
This blog post explores the importance of composing GraphQL fragments from multiple components into one query. It explains how this can make GraphQL safer and how it is often overlooked.

дэн
the results are always perfect
-
if you’re not composing GraphQL fragments from multiple components into one query (as Relay does), i think you’re missing 80% of the point of GraphQL.
— дэн (@dan_abramov) March 12, 2023
which is ok but isn’t talked about enough https://t.co/ooohCDV6ZO -
all original GraphQL presentations emphasized this: fragments allow composition!
— дэн (@dan_abramov) March 12, 2023
here it is in Lee’s talk: https://t.co/U9omaPNzSR
here it is in Jing’s talk: https://t.co/ICMO2ODGf8
i wonder why it’s rarely used in Apollo examples — i suspect the idea failed to sink in somehow -
i think Apollo supports fragments (https://t.co/19uaSK2QFn), but colocation as an idea is easy to miss. it does not appear to be taught as part of “thinking in Apollo”. i would totally walk away thinking you’re supposed to useQuery anywhere you want to fetch.
— дэн (@dan_abramov) March 12, 2023 -
if you want to “re-learn” GraphQL in React the way it was originally designed to be used (i.e. colocated fragments), this Relay guide is really good. check it out.
— дэн (@dan_abramov) March 12, 2023
the concepts probably apply to Apollo too (although not as efficient without a compiler):https://t.co/sGXt8QIYHJ -
this looks to be in the right direction to me for folks who don’t use Relay https://t.co/yLVR0LhGHT
— дэн (@dan_abramov) March 12, 2023 -
another important Relay idea is data masking.
— дэн (@dan_abramov) March 12, 2023
when you compose fragments with Relay, your component *only* sees the data you explicitly “asked for” in the fragment. even if the cache has more data!
this prevents accidental coupling between components.https://t.co/YI5MIz5UAF -
you can see data masking being discussed in this Apollo issue. but according to the thread, since Apollo does not have a build step, there is no natural way to implement data masking. https://t.co/ObYwTMPYle
— дэн (@dan_abramov) March 12, 2023 -
setting aside the Flux references (imo not super relevant), this is a good visualization for *why* the Relay approach makes sense https://t.co/EVGD6dV8L1
— дэн (@dan_abramov) March 12, 2023 -
another great explanation (not using Relay!) https://t.co/e6gYqwucrG
— дэн (@dan_abramov) March 12, 2023