Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Set Cookie in ReactJS ?
Next article icon

How to Set Cookie in ReactJS ?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cookies in React are used to set value in a key-value form which can be set in browser storage and used further for identifying the current user. The following example shows how to set the cookie in the ReactJS application, here we have taken the custom-cookie as key, which is set in the cookie with its value.

Approach

To set cookie in react we will use document.cookie property. We can also use external packages like js-cookie which simplify accessing cookie in react app.

Syntax:

// Setting cooking 
document.cookie = "name=value; expires=Thu, 01 Dec 2023 12:00:00 UTC; path=/";

// Accessing the cookie
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
};

Steps to Create React Application

Step 1: Create a React application using the following command:

npx create-react-app setcookiedemo

Step 2: After creating your project folder i.e. setcookiedemo, move to it using the following command:

cd setcookiedemo

Project Structure:

Project Structure

List of dependencies in the package.json file are:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: This example demonstrates setting and accessing cookie in react with the help of window.cookie property.

JavaScript
// App.js  import React, { useState } from "react";  const App = () => { 	const [message, setMessage] = useState(""); 	const [username, setUsername] = useState("");  	// Function to set a cookie 	const setCookieFunction = (name, value, days) => { 		let expires = ""; 		if (days) { 			const date = new Date(); 			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); 			expires = "; expires=" + date.toUTCString(); 		} 		document.cookie = name + "=" + value + expires + "; path=/"; 		setMessage(`Cookie set: ${name} = ${value}`); 	};  	// Function to get a cookie by name 	const getCookie = (name) => { 		const value = `; ${document.cookie}`; 		const parts = value.split(`; ${name}=`); 		if (parts.length === 2) return parts.pop().split(";").shift(); 		return null; 	};  	// Function to update the cookie 	const updateCookie = () => { 		setCookieFunction("custom-cookie", username, 7); // Set cookie for 7 days 	};  	// Function to retrieve cookie and display it 	const displayCookie = () => { 		const customCookie = getCookie("custom-cookie"); 		if (customCookie) { 			setMessage(`Retrieved Cookie Value: ${customCookie}`); 		} else { 			setMessage('No cookie found with the name "custom-cookie".'); 		} 	};  	return ( 		<div style={{ marginLeft: "200px" }}> 			<h2>Setting and Accessing Cookies in ReactJS</h2> 			<div> 				<span>Enter Value: </span> 				<input 					type="text" 					value={username} 					onChange={(e) => setUsername(e.target.value)} 					placeholder="Enter cookie value" 				/> 				<br /> 				<button onClick={updateCookie}>Set/Update Cookie</button> 				<br /> 				<button onClick={displayCookie}>Retrieve Cookie</button> 				<br /> 				<span style={{ fontWeight: "bold", color: "red" }}> 					{message} 				</span> 			</div> 		</div> 	); };  export default App; 

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

Output--set-cookie-in-react

Next Article
How to Set Cookie in ReactJS ?

G

gouravhammad
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • ReactJS

Similar Reads

    How to use SnackBar Component in ReactJS ?
    ReactJS provides developers with a wide range of components to create interactive and dynamic web applications. One such component is the SnackBar, which is commonly used to display temporary messages or notifications to users. Creating a SnackBar component allows for the presentation of these messa
    2 min read
    How to store single cache data in ReactJS ?
    Storing Data in a cache is an important task in web applications. We can cache some data into the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested. PrerequisitesReact JSCach
    2 min read
    How to Remove a Cookie in PHP?
    Cookies are small text files stored in a user's browser. It contain data such as user preferences, session information, and other relevant details. PHP cookies are used to store information that can persist across different web pages or sessions. At times, you may need to delete or remove a cookie,
    4 min read
    How to get single cache data in ReactJS ?
    We can use cache storage using window cache and in React JS to get single cache data. We can get single cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.
    2 min read
    How to Access HTTP Cookie in Node.js ?
    Cookies are small pieces of data sent by a server and stored on the client side, typically in the user's browser. They are often used to maintain stateful information such as user sessions, preferences, or tracking data. In Node.js, accessing and managing cookies is a common requirement for building
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences