Member-only story
Improve Your React Application Performance by Reducing the Number of API Calls
Request batching in React
I was recently working on a React application that needed to call an API to check if the user had permissions to perform different actions within the app. Components would check different permissions by calling this API and it was up to them to render an error or alternate state in case the user lacked the required permissions.
I noticed that this approach resulted in many calls being made in quick succession (although for different permissions) and I wanted to improve that by reducing the number of times this API was called. I then started thinking about how to implement a mechanism to debounce queries in a way that at the end of the waiting period (let’s say 10ms) it would collapse all the queries, make a single batch call and return the responses without the components knowing about it.
The API already supported a batch version (taking a list of permissions) so it was a frontend only effort.
A few years ago I worked on a API that used Hystrix, it was a Java library that provided many things including Request Collapsing, so I went on a quest to find a Javascript equivalent, I was really trying not to reinvent the wheel if possible.
And I found it! It’s dataloader:
a generic utility to be used as part of your application’s data fetching layer to provide a consistent API over various backends and reduce requests to those backends via batching and caching.
Table of Contents
· Dataloader usage
· React-query integration
Dataloader Usage
Basically, you define your Dataloader
:
const fetcher = async (requests) => {
// this function takes an array of collapsed requests makes a batch call and return an array of responses
};const loader = new Dataloader(fetcher);
And then use its promise-based API to load one (or more items):
const data = await loader.load(request);
By default, individual requests that occur within a single frame of execution will be collapsed. However, that is…