Open In App

How to store single cache data in ReactJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

Storing Data in a cache is an important task in web applications. We can cache some data into the browser and use it in our application whenever needed. 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 store single cache data in React JS we will use the Windows cache that helps to access the cache stored in the browser window. Define a function that accesses named data in the cache storage and then puts the custom data the user needs to store in the browser.

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: Created a addDataIntoCache function which takes the user data 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.

App.js




// Filename - App.js
 
import * as React from "react";
 
export default function App() {
    // Function to add our give data into cache
    const addDataIntoCache = (cacheName, url, response) => {
        // Converting our response into Actual Response form
        const data = new Response(JSON.stringify(response));
        console.log(data);
        if ("caches" in window) {
            // Opening given cache and putting our data into it
            caches.open(cacheName).then((cache) => {
                cache.put(url, data);
                alert("Data Added into cache!");
            });
        }
    };
 
    return (
        <div
            style={{
                height: 500,
                width: "80%",
                textAlign: "center",
                margin: "auto",
            }}
        >
            <h1 style={{ color: "green" }}>
                GeeksforGeeks
            </h1>
            <h4>Store data into cache in React JS</h4>
            <button
                onClick={() =>
                    addDataIntoCache(
                        "MyCache",
                        "https://www.geeksforgeeks.org/",
                        "SampleData"
                    )
                }
            >
                Add Data Into Cache
            </button>
        </div>
    );
}


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

Peek-2023-10-17-17-03



Last Updated : 02 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads