Skip to content
the poor coder

how to use cookies in react js

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

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:

Text

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC