API Optimisation techniques in frontend for CUD operations

Divyanshu Srivastava
VectoScalar
Published in
3 min readDec 7, 2023

There are three method by which in frontend can perform the CUD(create, update and delete) :

By performing the the cud operation and then

  1. if CUD API gives the success response then make the get API call for that module:

This is the most expensive because we making one extra API call after each CUD operation.

2. If API’s status code is success then we store/update the CUD API response in our store or show the updated data in the DOM:

In this at the time of creation backend need to send the unique id and frontend need to store the data send to backend (i.e payload) along with with the id to the store and show it on the DOM. There is a case where user is at page 2 and creating the data. So frontend can append the data in the page 2 at the top. When user refresh or come back at that page later on the data will be shown at the place where it should be.

This is the best optimized way to make the CUD API calls. Even if multiple users are updating the same data(i.e race condition)

3. This is a single user approach where their is no race condition arises(i.e single user is operating the single account):

In this approach after making the CUD operation frontend assumes the data is successfully updated in database. We doesn’t need to wait for the CUD API’S response. This is most complex but the fastest way to do any CUD operation from frontend. In this frontend need to make validations 100% accurate so that the data we are updating is absolutly correct and servers are reliable and robust enough. But in this approach there are some cases where frontend need to make the get API request like

a. When data is paginated and need to check the key is unique or not.

b. When Creating the data need to wait for API response as unique id need to be stored in our store.

Suggestion for backend:

  1. At the of creating return unique id assigned to that data.
  2. At the time of updating no data is need to send.
  3. Write the relevant message and status code.

Media storing in backend:

Frontend need to store the media best optimized way by converting the media to the latest formats and compress it (i.e if these are images it should be converted to webp, etc which takes 40% less storage). Because media is major factor on which loading time of API depends.

When frontend needs to implement the search:

If frontend needs to implement the search which is making the api call while typing the each word. Then there should be debounce(i.e. delay) in making the API calls. And we need to cancel the previous API call which is no longer needed by the user.

const delayedQuery = useCallback(debounce(q => sendQuery(q), 500), []);

Cancel axios requests on unmount:

It is one thing to write an asynchronous call to an API to fetch data, and it is another thing to cancel that call when it is not beneficial to our users. The single action of cancelling API request when it is no longer needed leads to a better performance. A common scenario where an API request needs to be cancelled is when a user navigates away from a page.

At the point the user navigates away from the page, all API requests made in it to update the state and render a view with the data is unnecessary and if not cancelled leads to memory leaks in an application. React alerts us to this problem by outputting these popular lines in the console. We can make a hook for handling this issue.

We can use the following approch to cancel the axios request:

import axios from 'axios';

const useAxiosGet = () => {
const cancelToken = axios.CancelToken.source();
const getData = (path, onDone, onError, params) => {
return new Promise((resolve, reject) => {
axios
.get(path, {
cancelToken: cancelToken.token,
...params,
})
.then((res) => {
if (onDone) onDone(res.data);
resolve(res);
})
.catch((err) => {
if (onError) onError(err);
reject(err);
});
});
};
const cancelRequests = () => {
if (cancelToken) cancelToken.cancel();
};
return [getData, cancelRequests];
};

export default useAxiosGet;
import React, { useEffect, useState } from 'react';
import useAxiosGet from './useAxiosGet';

function Review() {
const [setReview, review] = useState([]);
const [getData, cancelRequests] = useAxiosGet();
useEffect(() => {
getData('https://630c7a2583986f74a7c1d2b9.mockapi.io/review', setReview);
return cancelRequests;
}, []);
return <div>Review</div>;
}

export default Review;

--

--