DataLoader helps to group many small data requests into one big request. This makes fetching data faster and saves resources.
0
0
DataLoader for batching in GraphQL
Introduction
When you need to get data for many users at once in a GraphQL query.
When your app makes many small database calls that can be combined.
When you want to avoid asking the database the same question multiple times.
When you want to improve performance by reducing the number of requests.
When you have nested queries that fetch related data repeatedly.
Syntax
GraphQL
const DataLoader = require('dataloader'); const loader = new DataLoader(keys => batchLoadFunction(keys));
batchLoadFunction is a function that takes an array of keys and returns a Promise of an array of results.
DataLoader automatically groups keys and calls batchLoadFunction once per event loop tick.
Examples
This creates a DataLoader to batch load users by their IDs.
GraphQL
const userLoader = new DataLoader(userIds => batchGetUsers(userIds));
This DataLoader batches loading posts by their IDs.
GraphQL
const postLoader = new DataLoader(postIds => batchGetPosts(postIds));
A simple batch function that returns data for each key.
GraphQL
const loader = new DataLoader(keys => Promise.resolve(keys.map(key => fetchData(key))));
Sample Program
This example shows how DataLoader batches requests for users with IDs 1 and 2. The third request for ID 1 uses the cache.
GraphQL
const DataLoader = require('dataloader'); // Simulate database fetch function batchGetUsers(userIds) { console.log('Batch loading users:', userIds); return Promise.resolve(userIds.map(id => ({ id, name: `User${id}` }))); } const userLoader = new DataLoader(batchGetUsers); async function main() { const user1 = await userLoader.load(1); const user2 = await userLoader.load(2); const user3 = await userLoader.load(1); // Cached console.log(user1, user2, user3); } main();
OutputSuccess
Important Notes
DataLoader batches requests within the same event loop tick.
It caches results to avoid duplicate requests for the same key.
Always return results in the same order as the keys array.
Summary
DataLoader groups many small data requests into one batch.
It improves performance by reducing database calls.
It caches results to avoid repeated fetching.