Skip to content
Related Articles

Related Articles

Improve Article

How to check cache is already existing or not in ReactJS ?

  • Last Updated : 30 Apr, 2021

We can use the following approach in ReactJS to cache is already existing or not. We can check cache is already existing or not from the browser and use it in our application whenever needed. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested.

Approach: Follow these simple steps in order to check cache is already existing or not in ReactJS. We have created our isCacheAlreadyExisting() function which takes the cache name and returns true/false based on whether the given cacheName is already existing or not. When we click on the button, the function is triggered, and it checks cache is already existing or not. In the following example, we are trying to check whether CacheThree and CacheEight are already present in the browser or not, our browser has five caches named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below:

Creating 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. foldername, move to it using the following command:

    cd foldername

Project Structure: It will look like the following.

Project Structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.


import * as React from 'react';
export default function App() {
  // Function to check cache is already exisitng or not
  const isCacheAlreadyExisting = async ({ cacheName, url }) => {
    if (typeof caches === 'undefined') return false;
    let names = await caches.keys()
    var index = names.indexOf(cacheName)
    if(index > 0) {
    } else {
  // CacheThree to check 
  const cacheToCheceThree = {
    cacheName: 'CacheThree',
    url: 'https://localhost:300'
  // CacheEight to check 
  const cacheToCheckEight = {
    cacheName: 'CacheEight',
    url: 'https://localhost:300'
  return (
    <div style={{ height: 500, width: '80%' }}>
        How to check cache is already existing
        or not in ReactJS?
      <button onClick={() => isCacheAlreadyExisting(cacheToCheceThree)} >
        is Cache Three Already Existing</button> 
      <br />
      <button onClick={() => isCacheAlreadyExisting(cacheToCheckEight)} >
        is Cache Eight Already Existing</button>  
      <br />

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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :