how to use cookies in react js

How to Use Cookies in React JS

If you are working with React JS, you may need to use cookies for various reasons such as storing user preferences, keeping track of user sessions, or saving user data. Cookies are small text files that are stored on the user's computer and can be accessed by the web server.

The most common way to use cookies in React JS is by using the JavaScript document.cookie property. This property allows you to read, write, and delete cookies. Here is an example of how to set a cookie:


document.cookie = "key=value; expires=date; path=path";
  • key: The name of the cookie.
  • value: The value of the cookie.
  • expires: The expiration date of the cookie. You can use the JavaScript Date object to set a date in the future.
  • path: The path where the cookie is valid. By default, the cookie is valid for the current page.

To read a cookie, you can use the following code:


const cookies = document.cookie.split(';').reduce((acc, curr) => {
  const [name, value] = curr.trim().split('=');
  return { ...acc, [name]: value };
}, {});
console.log(cookies);

This code splits the cookies into an array, then uses the reduce method to convert it into an object, where each key represents a cookie name and its value represents the cookie value.

To delete a cookie, you can set its expiration date to a past date, like this:


document.cookie = "key=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Method 2: Using a Third-Party Library

If you don't want to use the document.cookie property directly, you can use a third-party library like React Cookie. This library provides a simple API for managing cookies in React JS.

Here is an example of how to use React Cookie:


import { useCookies } from 'react-cookie';

function App() {
  const [cookies, setCookie, removeCookie] = useCookies(['name']);

  function handleSaveCookie() {
    setCookie('name', 'value', { path: '/' });
  }

  function handleRemoveCookie() {
    removeCookie('name', { path: '/' });
  }

  return (
    <div>
      <p>Name: {cookies.name}</p>
      <button onClick={handleSaveCookie}>Save Cookie</button>
      <button onClick={handleRemoveCookie}>Remove Cookie</button>
    </div>
  );
}

This code imports the useCookies hook from the react-cookie library and uses it to manage a cookie named "name". The handleSaveCookie function sets the cookie value to "value" with a path of "/", while the handleRemoveCookie function removes the cookie.

Overall, there are multiple ways to use cookies in React JS, but using the JavaScript document.cookie property or a third-party library like React Cookie are the most common approaches.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe