Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to clear complete cache data in ReactJS ?

How to clear complete cache data in ReactJS ?

Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested. There is no direct option to clear the cache as it is a client-side feature managed by the browser. To clear the complete cache in React JS we can use JavaScipt’s cache storage API provided by the browser.

Approach

We will use JavaScript Cache storage API to access and manage the cache date present in the browser storage. Using cache storage API data with keys and IDs can provide access to specific resources. We will create a function that utilizes the cache storage API and deletes all cache data present in the browser storage.

In the following example, we have 5 caches stored in the browser named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below, and we clear the complete cache with the example given below.

Steps to create the application

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure

Project Structure

Example: Created our clearCacheData function which clears the entire cache data from the browser. When we click on the button, the function is triggered, and the entire caches get deleted from the browser, and we see an alert popup. 

JavaScript




// Filename: App.js
 
import * as React from "react";
 
export default function App() {
    // Function to clear complete cache data
 
    const clearCacheData = () => {
        caches.keys().then((names) => {
            names.forEach((name) => {
                caches.delete(name);
            });
        });
        alert("Complete Cache Cleared");
    };
 
    return (
        <div style={{ height: 500, width: "80%" }}>
            <h4>
                How to clear complete cache data in ReactJS?
            </h4>
            <button onClick={() => clearCacheData()}>
                Clear Cache Data
            </button>
        </div>
    );
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments