How to set cookies using React
In this post, let's see how to set cookies in React.
What is a Cookie?
A cookie is a piece of information that is stored inside the user's browser while browsing a site.
Installing package react-cookie
Run the below command to install the package
npm install react-cookie
or if you use yarn
yarn add react-cookie
Setting a cookie
First, import CookiesProvider
component and wrap your root component with it.
import { CookiesProvider } from "react-cookie";
.
.
<CookiesProvider>
<App />
</CookiesProvider>
We need to use the useCookies()
hook to set a cookie
import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
const [cookies_data, setCookie_data] = useCookies(["student"]);
return (
<div className="App">
<h1>React cookies</h1>
<button onClick={() => {
setCookie_data("student", "mani", {
path: "/"
});
}>Cookie</button> </div>
);
}
To access the cookie simply use the cookies_data.student