Install Cookie Package & Config
We’ll use the react-cookie package. It’s very popular. Run the below command to install it:
npm install react-cookie
Now we have to 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 App from './App';
import { CookiesProvider } from "react-cookie";
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
document.getElementById('root')
);
Set Cookie
To set a cookie, we need to import the useCookies() hook from the react-cookie package.
import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
const [cookies, setCookie, removeCookie] = useCookies(["user"]);
function handleSetCookie() {
setCookie("user", "obydul", { path: '/' });
}
return (
<div className="App">
<h1>React Cookie</h1>
<button onClick={handleSetCookie}>Set Cookie</button>
</div>
);
}
Access Cookie
We can retreive the user cookie uisng cookies.user. Here’s the example code:
import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
const [cookies, setCookie, removeCookie] = useCookies(["user"]);
function handleSetCookie() {
setCookie("user", "obydul", { path: '/' });
}
return (
<div className="App">
<h1>React Cookie</h1>
<p>{cookies.user}</p> {/* access user cookie */}
<button onClick={handleSetCookie}>Set Cookie</button>
</div>
);
}
Remove Cookie
The removeCookie() method is used to remove cookie. Have a look at the example:
import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
const [cookies, setCookie, removeCookie] = useCookies(["user"]);
function handleSetCookie() {
setCookie("user", "obydul", { path: '/' });
}
function handleRemoveCookie() {
removeCookie("user");
}
return (
<div className="App">
<h1>React Cookie</h1>
<p>{cookies.user}</p> {/* access user cookie */}
<button onClick={handleSetCookie}>Set Cookie</button>
<button onClick={handleRemoveCookie}>Remove Cookie</button>
</div>
);
}