How to delete specific cache data in ReactJS ?
Last Updated :
17 Nov, 2023
In React, we can access all cache data from the browser and delete specific cache data from the browser as per the user’s requirement whenever needed using the Cache Storage of the browser. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.
Prerequisites:
Approach:
To delete specific cache data in ReactJS we will create a deleteSpecificCache function which takes the cache name and deletes it from the browser cache. When we click on the button, the function is triggered, the given cache gets deleted from the browser, and we see an alert popup.
Steps to Create React 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. folder name, move to it using the following command:
cd foldername
Project Structure:
Project Structure
Example: This example shows how to delete specific cache data from browser using the window cache.
Javascript
import * as React from "react" ;
export default function App() {
const deleteSpecificCache = (cacheName) => {
if ( "caches" in window) {
caches. delete (cacheName).then( function (res) {
alert(cacheName);
return res;
});
}
};
return (
<div style={{ height: 500, width: "80%" }}>
<h4>
How to delete specific cache data in
ReactJS?
</h4>
<button
onClick={() =>
deleteSpecificCache( "MyCache" )
}
>
Delete Specific Cache
</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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...