What is Directive in GraphQL: Definition and Usage
directive is a special instruction that can be attached to fields or fragments to change their execution behavior dynamically. Directives like @include or @skip allow conditional fetching of data based on variables or conditions.How It Works
Think of a directive in GraphQL as a traffic signal for your query. It tells the GraphQL server whether to stop or go on certain parts of the query depending on conditions you set. This helps you control what data you want to fetch without changing the query structure itself.
For example, you might want to fetch a user's email only if a certain flag is true. Instead of writing two different queries, you use a directive to decide at runtime whether to include that field. This makes your queries flexible and efficient.
Example
This example shows how to use the @include directive to fetch a user's email only if a variable showEmail is true.
query getUser($showEmail: Boolean!) {
user(id: "1") {
name
email @include(if: $showEmail)
}
}When to Use
Use directives when you want to make your queries adaptable without writing multiple versions. They are perfect for:
- Conditionally including or skipping fields based on user input or app state.
- Reusing query fragments with different conditions.
- Optimizing data fetching to avoid unnecessary data transfer.
For example, in a social media app, you might want to show extra profile details only if the user is logged in. Directives let you handle this smoothly in one query.
Key Points
- Directives modify query execution dynamically.
- Common built-in directives are
@includeand@skip. - You can create custom directives for advanced use cases.
- Directives help reduce multiple query versions and improve efficiency.