How to Use useLazyQuery in Apollo Client for GraphQL
Use
useLazyQuery from Apollo Client to run GraphQL queries only when you want, not immediately on component render. It returns a trigger function to start the query and an object with query state like loading, data, and error. Call the trigger function when you want to fetch data.Syntax
The useLazyQuery hook returns a tuple: a trigger function and an object with query results and status.
- Trigger function: Call this to start the query.
- Result object: Contains
loading,data,error, and other info.
Example syntax:
javascript
const [triggerQuery, { loading, data, error }] = useLazyQuery(YOUR_GRAPHQL_QUERY, { variables: { /* optional variables */ }, onCompleted: () => { /* optional callback */ }, onError: () => { /* optional callback */ } });
Example
This example shows how to use useLazyQuery to fetch a list of books only when a button is clicked.
javascript
import React from 'react'; import { gql, useLazyQuery } from '@apollo/client'; const GET_BOOKS = gql` query GetBooks { books { id title author } } `; function Books() { const [getBooks, { loading, data, error }] = useLazyQuery(GET_BOOKS); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <button onClick={() => getBooks()}>Load Books</button> {data && ( <ul> {data.books.map(book => ( <li key={book.id}>{book.title} by {book.author}</li> ))} </ul> )} </div> ); } export default Books;
Output
<button>Load Books</button>
<ul>
<li>Book Title 1 by Author 1</li>
<li>Book Title 2 by Author 2</li>
...
</ul>
Common Pitfalls
- Calling the trigger function immediately defeats the purpose; it should be called on user action or event.
- Not handling loading and error states can cause bad user experience.
- Passing variables incorrectly or forgetting to update them when needed.
- Expecting data to be available before the trigger function is called.
Wrong way (calling query immediately):
javascript
// Wrong: calling triggerQuery immediately const [triggerQuery, { data }] = useLazyQuery(GET_BOOKS); // triggerQuery(); // This runs on every render, causing infinite loops // Right: call triggerQuery inside an event handler <button onClick={() => triggerQuery()}>Load</button>
Quick Reference
useLazyQuery Cheat Sheet:
| Part | Description |
|---|---|
| Trigger function | Call to start the query |
| loading | True while query is running |
| data | Query result data |
| error | Error info if query fails |
| variables | Optional variables for query |
| Part | Description |
|---|---|
| Trigger function | Call to start the query |
| loading | True while query is running |
| data | Query result data |
| error | Error info if query fails |
| variables | Optional variables for query |
Key Takeaways
useLazyQuery lets you run GraphQL queries on demand, not automatically.
Always call the trigger function inside an event or effect, not on every render.
Handle loading, error, and data states to improve user experience.
Pass variables correctly when calling the trigger function if needed.
useLazyQuery returns a tuple: a trigger function and an object with query state.