Skip to content
Related Articles

Related Articles

How to store multiple cache data in ReactJS ?

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Apr, 2022

We can use the following approach in ReactJS to store multiple cache data in ReactJS. We can store multiple cache data into 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 store multiple cache data in ReactJS. We have created our addMultipleCacheData function which takes the user data list and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup. In the following example, we are trying to store multiple caches named CacheOne, CacheTwo, and CacheThree using our defined function.

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

cd foldername

Project Structure: It will look like the following.

Project Structure

Example: 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 add our give multiple cache data
  const addMultipleCacheData = async (cacheList) => {

    for (var i = 0; i < cacheList.length; i++) {
      // Converting our respons into Actual Response form
      const data = new Response(JSON.stringify(cacheList[i].cacheData));

      if ('caches' in window) {
        // Opening given cache and putting our data into it
        var cache = await[i].cacheName)
        cache.put(cacheList[i].url, data);
    alert('Multiple Cache Stored!')

  const CacheToBeStored = [
    { cacheName: 'CacheOne', cacheData: '1 CacheData', 
    url: 'https://localhost:300' },
    { cacheName: 'CacheTwo', cacheData: '2 CacheData', 
    url: 'https://localhost:300' },
    { cacheName: 'CacheThree', cacheData: '3rd CacheData', 
    url: 'https://localhost:300' },

  return (
    <div style={{ height: 500, width: '80%' }}>
      <h4>How to store multiple cache data in ReactJS?</h4>
      <button onClick={() => addMultipleCacheData(CacheToBeStored)} >
        Add Multiple Caches</button>

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 :

Start Your Coding Journey Now!