by Sai gowtham

Getting the browser cookie in React

In this tutorial, we are going to learn about how to get a cookie’s from the browser in React using the react-cookie package.

The react-cookie package helps us to get and set the cookies from the browser.

Let’s install it by running the following command.

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

Now, inside your React component, you can access the cookie by using a useCookies() hook.

App.js
import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
  const [cookies, setCookie] = useCookies();
  return (
    <div className="App">
      <h1>React cookies</h1>
      {cookies.user && <p>{cookies.user}</p>}    </div>
  );
}

The cookies object is holding the all cookies, you have created in your app.

In class-based components, you can get the cookie by using a withCookies() higher-order component.

App.js
import React, { Component } from "react";
import { withCookies } from "react-cookie";
class App extends Component {

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

  render() {
    const { user } = this.state;    return (
      <div className="App">
        {user && <p>{user}</p>}      </div>
    );
  }
}

export default withCookies(App);

These are some cases you can’t get a cookie in React:

  • If you don’t set a cookie path as / then you can’t access a cookie from all pages.
  • If you set an httpOnly cookie to the response, then you can’t access it inside the react app, because the browser directly embeds the cookie to an HTTP header.

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