Clear Complete Cache Data in ReactJS



Caching is a technique used to store reusable resources in the user's browser. Caches are of different types, for example, Local Storage Cache, Session Storage Cache, and Service Worker Cache, each of these has a different approach to clearing completely from browser. In this article, we will explain how to clear all caches in a React app.

What is Cache?

Caches are temporarily stored resources on a web page such as variables, user preferences, images, style sheets, scripts, etc. These are used to reduce server load and speed up page load times by reusing previously fetched resources. Following are common types of caches used on client side:

  • Service Worker Cache: Service workers use the Cache API to store some resources such as CSS files, and JavaScript files to reduce number of calls to a server. It is commonly used in Progressive Web Apps (PWAs).
  • Browser Storage Cache: The browser can store JavaScript variables such as username, password, or even big files like images in the browser's local storage. There are two types, localStorage and sessionStorage.
  • Application State Cache: These are used in state management tools like Redux to store user states in browser.

Cache Storage API

The Cache Storage API is a modern web storage feature that is used by developers to programmatically store and retrieve network requests and their corresponding responses. With this, developers can manually add, delete, and retrieve cache entries. Following are basic methods in cache storage API.

//Creates a cache with the given name
caches.open(cacheName)

//Add a single request-response pair to the cache
cache.add(request)

// Deletes a cache by name
caches.delete(cacheName)

// Searches for a response in the cache that matches the request
cache.match(request)

// List all available caches
caches.keys()

Steps to Clear Complete Cache Data

The following section explains process of clearing different types of caches in your React project.

Step 1: Clear Local Storage and Session Storage

The local storage and session storage are commonly used caches to store reusable variables such as usernames, passwords, color-theme of the user, etc. Local storage remains forever until cleared, while session storage will be lost on reloading the page. You can use localStorage.clear() and sessionStorage.clear() to clear all data stored in local and session storage.

// Set data in local storage
localStorage.setItem("username", "Farhan");

// Set data in session storage
sessionStorage.setItem("sessionID", "12345");

// Clear both
localStorage.clear();
sessionStorage.clear();

Step 2: Clear Service Worker Cache

Service Worker Cache is used to store stylesheets and script files inside the user's browser to minimize requests to a server. The following code shows how to store CSS and JavaScript files in cache and clear those programmatically.

const CACHE_NAME = 'simple-cache';

// Setup Service Cache
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      cache.addAll(['/styles.css', '/script.js']);
    })
  );
});

// Clear the cache
if ('caches' in window) {
    caches.keys().then((cacheNames) => {
      cacheNames.forEach((cacheName) => {
        caches.delete(cacheName);
      });
    });
}  

Step 3: Clear Application State

In state management tools like Redux, to clear or reset the application state we need to dispatch an action that resets the reducer's state to its initial value. For example, Let's say we have an application with a user's authentication state, and we need to clear it when the user is logging out, we can define an action.js file with the following code.

// actions.js
export const RESET_STATE = 'RESET_STATE';

export const resetState = () => ({
  type: RESET_STATE,
});

Step 4: Clear Cookies

Cookies contain small pieces of user-specific data such as login state, pand references. To clear cookies, we can use document.cookie property. With this property, we can define a cookie, set an expiration date for a cookie, or delete all the cookies. See the code below.

//Defining a new Cookie and Set Expiration
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

//Delete all cookie in a page
document.cookie.split(";").forEach((c) => {
    document.cookie = c
      .replace(/^ +/, "")
      .replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`);
  });

Step 5: Browser-Level Cache Clearing

Browser-level cache is a feature of web browsers that stores resources such as HTML files, CSS stylesheets, JavaScript files, images, and other web assets locally on the user's device. These are features of web browsers and developers can't programmatically clear this cache from browsers. Users can clear the browser cache manually through browser settings.

  • Chrome: Settings > Privacy and Security > Clear Browsing Data
  • Edge: Settings > Privacy, Search, and Services > Clear Browsing Data
  • Firefox: Options > Privacy & Security > Cookies and Site Data

Example: Cache Clearing In React

In the example below we defined a App.js file and clear-cache.js component. App.js file will create a cache and clear-cache.js define a button to clear the cache.

File - App.js

In App.js file, we will add some cache to local and session storage using useEffect Hook, Then we call the clear-cache component where we define logic to clear cache.

import React, { useState, useEffect } from "react";
import ClearCacheButton from './components/clear-cache';

const App = () => {
  // Add some data to localStorage and sessionStorage
  useEffect(() => {
    // Add to localStorage
    localStorage.setItem('username', 'Farhan');
    localStorage.setItem('theme', 'green');

    // Add to sessionStorage
    sessionStorage.setItem('sessionId', '123456');
    sessionStorage.setItem('isLoggedIn', 'true');
  }, []);

  return (
        <div>
        <h1>React Cache Management</h1>
        <p>Cache has been set. Click the button below to clear the cache.</p>

        /* Calling Clear Cache button */
        <ClearCacheButton />
        </div>
  );
};

export default App;

File - clear-cache.js

The clear-cache component will define a button, which when clicked all cache storages are removed. This component will be exported to App.js file.

 import React from 'react';

const ClearCacheButton = () => {
  const clearCache = () => {
    // Clear Local Storage and Session Storage
    localStorage.clear();
    sessionStorage.clear();

    // Clear Service Worker Cache
    if ('caches' in window) {
      caches.keys().then((cacheNames) => {
        cacheNames.forEach((cacheName) => {
          caches.delete(cacheName);
        });
      });
    }

    // Clear Cookies
    document.cookie.split(";").forEach((c) => {
      document.cookie = c
        .replace(/^ +/, "")
        .replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`);
    });

    alert('Cache cleared!');
  };

  return <button onClick={clearCache}>Clear Cache</button>;
};

export default ClearCacheButton;   

Output

Following is output for the above code. Notice that, we opened the Application tab of inspect section (in Chrome dev tools) to understand the removal of caches in real time.

React Cache Clear Output

Best Cache Management Strategies in React

Here are some recommended cache management strategies for React.

  • Implement Cache Versioning: Cache versioning involves organizing cached resources into distinct versions. Each version of your app's cache corresponds to a specific version of your app's resources. For example, if your app evolves from version 1 to version 2, you can name the caches v1 and v2, respectively, and delete the older cache when the app is updated
  • Use Browser Storage for App-Specific Data Clearing: LocalStorage and SessionStorage are browser storage mechanisms suitable for caching small, app-specific data such as user preferences, temporary states, or session data. Using these storage options for non-critical or app-specific data simplifies cache management.
  • Add Cache-Busting Techniques: Cache-busting ensures that users receive the latest versions of your app's assets by forcefully reloading resources from a server. You can achieve this by appending query parameters to resource URLs, such as version numbers or timestamps (e.g., /style.css?v=2). When a URL changes, browsers treat it as a new resource and fetch the updated version from the server
Updated on: 2024-11-29T12:11:40+05:30

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements