How to use cookies in React js?
December 22, 2024Hi Friends 👋,
Welcome To aHoisting!
To use cookies in react js, you have to use hooks like useCookies
for an intuitive that’s how you can use cookies in react js.
Today, I am going to show you, how to use cookies in react js.
Installation
Install the following packages to use cookies in react js.
npm
npm install react-cookie
yarn
yarn add react-cookie
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Let’s start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React from "react";
import { useCookies } from "react-cookie";
Step 3: Create a Component.
You can use onClick={setCookieHandler}
to use cookies in react js.
<div>
<button onClick={setCookieHandler}>Set Cookie</button>
<button onClick={getCookieHandler}>Get Cookie</button>
<button onClick={removeCookieHandler}>Delete Cookie</button>
</div>
Use cookies example.
The below code is an example of a React. You have to import "react-cookie"
and use hooks like useCookies
for an intuitive to use cookies in react js.
App.js
import React from "react";
import { useCookies } from "react-cookie";
const ReactCookieExample = () => {
const [cookies, setCookie, removeCookie] = useCookies(["username"]);
// Set a cookie
const setCookieHandler = () => {
setCookie("username", "JohnDoe", { path: "/" });
};
// Get a cookie
const getCookieHandler = () => {
console.log(cookies.username); // Access the cookie
};
// Delete a cookie
const removeCookieHandler = () => {
removeCookie("username");
};
return (
<div>
<button onClick={setCookieHandler}>Set Cookie</button>
<button onClick={getCookieHandler}>Get Cookie</button>
<button onClick={removeCookieHandler}>Delete Cookie</button>
</div>
);
};
export default ReactCookieExample;
In the above code example, I have used the "react-cookie"
to use cookies in react js.
Check the output of the above code.
All the best 👍