How To Set Cookie In React

Hello,

In this post, we’ll look at how to use the react-cookie package to set a cookie on a webpage in React.

A cookie is a little piece of data (key-value pairs) that the web browser saves on the user’s computer while they are accessing a website. Cookies are intended to provide a secure way for websites to remember stateful information, track user browsing activities, and authenticate user identity.

To set and get cookies, we must first install the react-cookie(npm) package in our project.

To install it, use the command below.

npm install react-cookie

To begin, take the CookiesProvider component from the react-cookie package and wrap it around your root app component.

  • index.js:
import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <CookiesProvider>
    <App />
  </CookiesProvider>,
  rootElement
);

To set a cookie, we’ll need to import the react-cookie package’s useCookies() hook.

The useCookies() hook takes an array as its first argument and returns an array with two elements: a cookies object and the setCookie() method.

All of the cookies you’ve created in your app are stored in the cookies object.

The cookie is set using the setCookie() method.

Example:

  • App.js:
import React from "react";
import { useCookies } from "react-cookie";

export default function App() {
  const [cookies, setCookie] = useCookies(["user"]);

  function handleCookie() {
    setCookie("user", "gowtham", {
      path: "/"
    });
  }
  return (
    <div className="App">
      <h1>React cookies</h1>
      <button onClick={handleCookie}>Set Cookie</button>
    </div>
  );
}

We gave three inputs to the setCookie() method in the preceding code: cookie-name, cookie-value, and options object, with path: "/" being used to access the cookie across all pages.

Visit this website for more options such as cookie duration, httpOnly, secured, and so forth.

This is how you can get to the cookie.

  • App.js:
import React from "react";
import { useCookies } from "react-cookie";

export default function App() {
  const [cookies, setCookie] = useCookies(["user"]);

  function handleCookie() {
    setCookie("user", "gowtham", {
      path: "/"
    });
  }
  return (
    <div className="App">
      <h1>React cookies</h1>
       {cookies.user && <p>{cookies.user}</p>}
      <button onClick={handleCookie}>Set Cookie</button>
    </div>
  );
}

Output:

Cookies

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories