Include vs Skip Directive in GraphQL: Key Differences and Usage
@include directive includes a field only if a specified condition is true, while the @skip directive excludes a field if a specified condition is true. Both directives use a if argument to control whether a field or fragment is included in the query result.Quick Comparison
This table summarizes the main differences between the @include and @skip directives in GraphQL.
| Aspect | @include Directive | @skip Directive |
|---|---|---|
| Purpose | Includes field if condition is true | Skips field if condition is true |
| Condition Argument | if: Boolean! | if: Boolean! |
| Default Behavior | Field excluded if if is false | Field included if if is false |
| Use Case | Add field only when needed | Remove field when not needed |
| Logical Relation | Positive condition | Negative condition |
Key Differences
The @include directive in GraphQL is used to conditionally add a field or fragment only when the if argument evaluates to true. This means if the condition is false, the field is omitted from the response entirely. It is useful when you want to add optional data based on some client-side logic.
On the other hand, the @skip directive works oppositely: it excludes a field or fragment when the if argument is true. If the condition is false, the field remains in the response. This directive is handy when you want to remove data conditionally.
Both directives accept a required Boolean argument named if. They cannot be used together on the same field because their conditions conflict. Choosing between them depends on whether you prefer to specify when to include or when to exclude a field.
Code Comparison
query GetUser($showEmail: Boolean!) {
user {
id
name
email @include(if: $showEmail)
}
}@skip Directive Equivalent
query GetUser($hideEmail: Boolean!) {
user {
id
name
email @skip(if: $hideEmail)
}
}When to Use Which
Choose @include when you want to explicitly add a field only if a condition is true, making your query intent clear about adding optional data. Use @skip when you want to exclude a field based on a condition, which can be more intuitive if you think in terms of removing data.
In practice, @include is often preferred for adding optional fields, while @skip is useful for hiding sensitive or unnecessary data. Avoid using both on the same field to prevent confusion.
Key Takeaways
@include(if: Boolean) to add fields only when a condition is true.@skip(if: Boolean) to remove fields when a condition is true.@include and @skip together on the same field.