Skip to content
Related Articles
Open in App
Not now

Related Articles

How to set Cookie in ReactJS ?

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 16 Dec, 2020
Improve Article
Save Article

Cookies are an important part of an application because cookies 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 username as key, which is set in the cookie with its value.

Creating 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: It will look like the following.

Project Structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to set cookies in localStorage with basic UI.


import React, { useState } from "react";
const App = () => {
  const [message, setMessage] = useState('')
  const setCookieFunction = (value) => {
    localStorage.setItem('username', value)
    setMessage('Username set as cookie!!')
  return (
    <div style={{
      marginLeft: '200px',
        <h2>Setting Cookie in ReactJS</h2>
        <span>Enter User Name: </span><input type="text" 
        onChange={(e) => setCookieFunction(}></input> <br />
        <span style={{
          fontWeight: 'bold',
          color: 'red',
export default App

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

npm start


  1. The following will be the output if the user enters a username which is set as a cookie as shown below:

  2. Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!