Q8: What are GraphQL Fragments and why are they used?
A fragment is a reusable unit of a GraphQL query. It allows developers to construct sets of fields and include them in multiple queries, preventing code duplication.
GraphQL Fragment Example
fragment UserFields on User {
id
name
email
}
query GetUser {
user(id: "1") {
...UserFields
}
}💡 The fragment
UserFields is reused using the spread syntax (...UserFields).Key Takeaways
- Fragments eliminate duplicate field selections across queries.
- They are vital for UI components that define their own data dependencies.
Knowledge Check
Which operator is used to apply a fragment inside a query?