In modern FrontEnd applications, performance is a key factor for user experience. One effective way to enhance performance is by caching the results of service (HTTP requests) functions. This reduces redundant network requests and computations.
In this article, we'll explore the http-front-cache
utility, which provides a simple and efficient way to caching on the Frontend.
By the way, it is opensource 🚀
What is http-front-cache?
http-front-cache
is a utility designed to cache the results of service functions in the browser. However, it's important to use this utility with caution and adhere to certain constraints:
- The data to be cached should not be too large.
- The data should not be sensitive.
- The data should not change too often.
- The service parameters should not change too often (if they change too often, the cache will not be used).
By default, http-front-cache
provides two helper functions:
cacheFactory
: An extendable cache factory function that accepts a provider (place to save the cache) to cache data. This allows you to extend the caching mechanism and save your cache wherever you need, such as localStorage, sessionStorage, IndexedDB, cookies, in-memory, and etc.
cacheOnSessionStorage
: cacheOnSessionStorage is a ready cacheable function that uses cacheFactory
and defines Session Storage as a provider. It is an example of what cacheFactory
can do. cacheOnSessionStorage
was created as Session Storage is one of the most used cache data providers on FrontEnd.
Installation
To get started with http-front-cache
, you can install it via npm:
npm i @openish-u/http-front-cache
How to Use http-front-cache
As you might noticed, there are two way to use http-front-cache
1) Using cacheOnSessionStorage
import { cacheOnSessionStorage } from 'utility-http-front-cache';
type Params = string;
type Result = { data: string[] };
const fetchData: ServiceFunction<Params, Result> = async (param: string) => {
const response = await fetch(`https://dev.to/api/articles?${param}`);
return response.json();
};
const cachedFetchData = cacheOnSessionStorage(fetchData, 5 * 60 * 1000); // Cache for 5 minutes
// Usage
cachedFetchData('exampleParam').then((result) => {
console.log(result); // result is the data returned from fetchData
});
// export cachedFetchData and use where you need
In this example, we define a service function fetchData
that fetches data from an API. We then use cacheOnSessionStorage
to cache the results of this function for 5 minutes. When cachedFetchData
is called, it will first check the cache before making a network request.
Enjoying it? If so, don't forget to give a ❤️ _ and follow me to keep updated. Then, I'll continue creating more content like this_
2) Extending http-front-cache with Custom Providers
import { cacheFactory, ServiceFunction, Provider} from 'utility-http-front-cache';
const customProvider: Provider = {
getItem: (key) =>
JSON.parse(localStorage.getItem(key) as string) as Uint8Array,
setItem: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
removeItem: (key) => localStorage.removeItem(key),
};
export const cacheOnMyCustomProvider = <TParams extends unknown[], TResult>(
serviceFunction: ServiceFunction<TParams, TResult>,
expire: number
): ServiceFunction<TParams, TResult> => {
return async (...params: TParams): Promise<TResult> => {
return cacheFactory<TParams, TResult>({
params,
expire,
serviceFunction: fetchData,
provider: customProvider,
});
};
};
// Usage
const cachedFetchData = cacheOnMyCustomProvider(fetchData, 5 * 60 * 1000); // Cache for 5 minutes
// cacheOnMyCustomProvider is your own cache function 😍
cachedFetchData('exampleParam').then((result) => {
console.log(result); // result is the data returned from fetchData
});
// export cachedFetchData and use where you need
In this example, we define a custom provider with getItem
, setItem
and removeItem
methods. We then use cacheFactory
to create a caching function that uses our custom provider. The same can be done to cache the data where you need it. xP
Buy me a coffee ☕. Hope I have helped you somehow. 🤗
Conclusion
http-front-cache
is a powerful utility that can help you boost the performance of your web applications by caching service function results.
For more information and the latest updates, check out the full documentation on GitHub.
Top comments (0)