Utilizing Browser Cache and Cookies in React.js Applications

Introduction

Using cache and cookies in React.js applications involves storing data locally on the user's device for various purposes, such as improving performance or persisting user preferences. Below, I'll provide step-by-step instructions on how to use cache and cookies in React.js applications.

Step 1. Create a React Application

If you haven't already, set up a React.js application. You can use Create React App or any other method you prefer.

npx create-react-app react-cache-cookies-demo
cd react-cache-cookies-demo
npm start

Step 2. Using localStorage for Cache

In this step, we'll use localStorage to store and retrieve data in the browser cache. Let's say you want to store and retrieve a user's name.

// src/App.js

import React, { useState } from 'react';

function App() {
  const [name, setName] = useState(localStorage.getItem('userName') || '');

  const handleNameChange = (event) => {
    const newName = event.target.value;
    setName(newName);
    localStorage.setItem('userName', newName); // Store the name in localStorage
  };

  return (
    <div>
      <h1>Hello, {name || 'Stranger'}!</h1>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={handleNameChange}
      />
    </div>
  );
}

export default App;

Here, we're using localStorage.setItem to store the user's name and localStorage.getItem to retrieve it. The name will persist even if the user closes the browser and returns later.

Step 3. Using the js-cookie Library for Cookies

In this step, we'll use the js-cookie library to set, retrieve, and delete cookies.

First, install the js-cookie library:

npm install js-cookie

Now, let's create a simple example of setting and retrieving a cookie with 'js-cookie'.

// src/App.js

import React from 'react';
import Cookies from 'js-cookie';

function App() {
  const setCookie = () => {
    Cookies.set('userToken', 'exampleToken', { expires: 7 }); // Set a cookie that expires in 7 days
  };

  const getCookie = () => {
    const userToken = Cookies.get('userToken'); // Get the value of the cookie
    alert(`User Token: ${userToken || 'Not found'}`);
  };

  const deleteCookie = () => {
    Cookies.remove('userToken'); // Remove the cookie
  };

  return (
    <div>
      <button onClick={setCookie}>Set Cookie</button>
      <button onClick={getCookie}>Get Cookie</button>
      <button onClick={deleteCookie}>Delete Cookie</button>
    </div>
  );
}

export default App;

In this example, we have three buttons to set, get, and delete a cookie named userToken. The cookie will expire in 7 days.

Step 4. Testing Your React Application

Run your React application using npm start, and you can test the cache and cookie functionalities in your browser.

  • When you enter your name in the input field and refresh the page, your name should still be displayed from localStorage.
  • Click the "Set Cookie" button to set a cookie.
  • Click the "Get Cookie" button to retrieve and display the cookie's value.
  • Click the "Delete Cookie" button to remove the cookie.

That's it! You've successfully implemented browser cache and cookies in a React.js application. You can now apply these concepts to more complex scenarios and customize them to suit your application's needs.

Summary

By following these steps and best practices, you can effectively use cache and cookies in your React.js applications to enhance user experiences, improve performance, and store data seamlessly.