Author -  Sai gowtham

How to set a cookie in React

In this tutorial, we are going to learn about how to set a cookie to the webpage in react using the react-cookie package.

A cookie is a piece of data (key-value pairs) that is stored on the user’s computer by the web browser while browsing a site. Cookies are designed to be a reliable mechanism for websites to remember stateful information or to record the user’s browsing activity or verify the user identity.

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

Run the below command to install it.

npm install react-cookie

First, import the CookiesProvider component from the react-cookie package and wrap your root app component with it.

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 need to import the useCookies() hook from the react-cookie package.

The useCookies() hook accepts the array with cookie-name as it’s first argument and returns the array with two elements cookies object , setCookie() method.

The cookies object contains all cookies you have created in your app.

The setCookie() method is used to set the cookie.

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>
  );
}

In the above code, we have passed three arguments to the setCookie() method, first one is cookie-name, second is cookie-value and third is options object where we used path: "/" to access the cookie in all pages.

For more options like cookie duration, httpOnly, secured, etc you can visit this url.

You can access the cookie like this.

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>
  );
}

In class-based components, we need to use withCookies() higher-order component to set and get cookies.

Here is an example:

App.js
import React, { Component } from "react";
import { instanceOf } from "prop-types";
import { withCookies, Cookies } from "react-cookie";
class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired  };

  state = {
    user: this.props.cookies.get("user") || ""
  };

  handleCookie = () => {
    const { cookies } = this.props;
    cookies.set("user", "gowtham", { path: "/" }); // setting the cookie    this.setState({ user: cookies.get("user") });
  };

  render() {
    const { user } = this.state;
    return (
      <div className="App">
        <h1>React cookies</h1>
        {user && <p>{user}</p>}        <button onClick={this.handleCookie}>Set Cookie</button>      </div>
    );
  }
}

export default withCookies(App);

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY