Incrementally load GraphQL query data with the new @defer directive
GraphQL is a popular query language used for building APIs that offer a flexible and efficient way to retrieve data from servers. It comes with a set of powerful directives that can be used to manipulate the query execution process.
One of the biggest disadvantages of GraphQL is that not all data resolvers are of equal importance. Certain fields may be very expensive to query which can lead to unintentionally long loading states. Given that apps can typically function on a subset of data, we’ve previously relied on solutions such as splitting queries and pre-fetching data to achieve this.
In this article, we’ll explore how the powerful new @defer directive can help us achieve this a lot more simply.
What is the @defer directive?
The @defer
directive is used in GraphQL to indicate that a field should be deferred and evaluated later, after an initial query response has been sent. This can be useful in cases where a field is expensive to compute or involves asynchronous operations.
Consider the following example:
query getUser {
user(id: 123) {
name
posts {
title
}
friends @defer {
id
name
}
}
}