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.
What is Cookie?
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.
Installing the react-cookie package
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
Setting the Cookie with React hooks
First, import the CookiesProvider
component from the react-cookie
package and wrap your root app component with it.
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:
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.
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:
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);