iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Fragments

Fragments are reusable selection sets — the “named sub-query” for fields you select the same way in several places. Inline fragments handle union and interface unwrapping.

Named, inline, spread, dedup

EXAMPLE
# 1) Named fragment — reuse field selections
fragment PostFields on Post {
    id
    title
    publishedAt
    author { name avatar }
    tags { name }
}

query Feed {
    feed   { ...PostFields }
    pinned { ...PostFields }
    drafts { ...PostFields }
}

# 2) Compose — fragments can include other fragments
fragment AuthorPreview on User {
    id
    name
    avatar
}

fragment PostFull on Post {
    ...PostFields
    body
    relatedPosts { ...PostFields }
    author       { ...AuthorPreview }
}

# 3) Inline fragment — for interfaces / unions
query Search($q: String!) {
    search(q: $q) {
        __typename
        ... on Post {
            id
            title
        }
        ... on User {
            id
            email
        }
        ... on Comment {
            id
            body
            post { id title }
        }
    }
}

# 4) Type-conditioned with @include / @skip
query Post($id: ID!, $withComments: Boolean!) {
    post(id: $id) {
        ...PostFields
        ...on Post @include(if: $withComments) {
            comments(first: 10) { id body }
        }
    }
}

# 5) Apollo / Relay — fragments live next to the component
# UserCard.gql
fragment UserCard on User {
    id
    name
    avatar
    role
}

# parent
query Header($uid: ID!) {
    user(id: $uid) { ...UserCard }
}

# 6) Avoid the n+1 with fragments — same fields, ONE round trip
# BAD — two parallel queries hit the server twice + double-serialise the User type
# GOOD — one query, one cache hit:
query Page($uid: ID!) {
    me:        user(id: $uid) { ...UserCard }
    suggested: suggestedUsers { ...UserCard }
}

Why it matters

Co-locate fragments next to the components that read them. Relay enforces this; Apollo encourages it. Each component owns its data dependencies, and the parent query is auto-composed at build time.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
fragment UserCore on User { id name email }
query { me { ...UserCore role } }
Try it Yourself »

Exercise

Reusable selection block keyword.

UserCore on User { id name }

Discussion

Loading…