by 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.

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course