Client-side Caching in React with Typescript

This Post show how to cache data in Single-Page-Applications, This method can be implemented on other Frameworks also.

ยท

3 min read

Client-side Caching in React with Typescript

This method is used in this portfolio site, So you can easily implement this method.

Create a new React Project with Typescript Support using the command

npx create-react-app <name> (or) npm create vite@latest

Create a typescript file Naming with CacheService or Anything Related to Cache ๐Ÿ˜…. Create a class with name similar as the and export It,

export class CacheService { }

then create a private static variable with name **data **

export class CacheService 
{
  private static data: { key: string; value: any; }[] = []
}

Add a static method to the class with Set as the name that accepts 2 arguments

  • Key

  • Value ( Generic )

  public static Set<T>(key: string, value: T) 
  {
    let contains = false;
    this.data.forEach(x => {
  if(x.key === key) 
  {
    contains = true;
  }
    });
    if (contains) {
  this.data = this.data.filter(x => x.key !== key);
    }
    this.data.push({ key, value });
  }

The complete method looks like this.

Then moving on to the Getting a value based on the key that's been passed.

Add a static method to the class with Get as the name that accepts 1 argument i,e **Key. **

Note: This Get method is also a Generic method.

public static Get<T>(key: string): T | any | null {
  let val: T | any | null = null;
  this.data.filter(x => {
if (x.key === key)val = x;
  });
  return val?.value;
}

Now GetAll Method. This method is so simple to implement i,e Returning the data itself ๐Ÿ˜€.

public static GetAll() {
  return this.data;
}

Now It's Time to implement whether the key exists or not in the cache. This is also simple to implement.

public static HasKey(key: string) {
  let flag = false;
  this.data.forEach(x => {
if (x.key === key) {
  flag = true;
}
  });
  return flag;
}

Now the Last part is to make a method to delete data from Cache. This accepts only key and returns whether the data is deleted from Cache or not.

public static Delete(key: string): boolean {
  let flag = false;
  this.data = this.data.filter(x => {
if(x.key === key) {
  flag = true;
}
return x.key !== key;
  })
  return flag;
}

Now the final Part is to Use and Test the written code.

To Get the data from the cache, simply call the ' CacheService.Get(key, value) ' method

const loggedIn = CacheService.Get<boolean>("login");
if (loggedIn) {
  console.log('You are Logged in');
} else {
  console.log('Please login again.');  
}

To Set a value to Cache

CacheService.Set("login", true);

To check whether a key exists in the Cache or not

const contains = CacheService.HasKey("login");
if(contains) {
  console.log("Exists in Cache");
} else {
  console.log("Does not exists in Cache");
}

To Delete a key in Cache

const deleted = CacheService.Delete("login");
if(deleted) {
  console.log("Successfully deleted from Cache");
} else {
  console.log("Key Doesn't Exist in Cache");
}

This way, we can cache any type of data in-memory using this method. I've used this method in this Portfolio Site.

Caching can be very useful in RESTful Applications where data can be cached on client-side and we need not request every time the page loads.

Get the Full File here Click here.

NOTE: This method works only on Single-Page-Applications (SPA's). Once User refreshes the page, the cache will be cleared.
ย