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
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: