Conquer Cookie Chaos in React.js: Introducing the useCookies Hook

Rahul Kumar
3 min readApr 11, 2024

--

useCookies:

  • Cookies is a simple text document
  • Purpose of Cookies:
    - It can store client authentication details.
    - Cookies are used by web application to store client authentication details and use across multiple requests and components until removed.
  • Authentications details can be stored as two way:
    a) Temporary (In-memory cookie)
    b) permanent
  • If cookie is temporary then it is also called as “In-memory cookie”. it is deleted automatially when browser is closed.
  • If cookie is permanent then it is also called persistent, and It can be stored in your HDD for a duration off specific time Interval.
  • Cookies can Infected by Virus.
  • Cookies can be disabled by browser.

Q How a developer known the status of cookies on client browser?
- By using JavaScript “navigator” object.

navigator.cookieEnabled = true/false;
navigator.appName
navigator.plugins[]

How to use Cookie in ReactJS?

React allows developers to use various third party cookie libraries “react-cookie”.

Install react-cookie:

npm install react-cookie --save
  • Cookie is provided as a service by “react-cookie” library:

The provider is

<CookiesProvider>
// Scope of Cookie
// The components that have to use cookie must be with in scope of cookie provider
</CookiesProvider>
  • The cookies are created by “useCookies” hook and also responsible for creating, reading and removing cookies.

Syntax:

Configure Cookie:

const [cookies, setCookie, removeCookie] = useCookies(['cookiename'])

Creating Cookie:

setCookie('cookiename', 'cookievalue', {cookieOptions});

setCookie('cookiename', 'cookievalue',{path: '/', expires: new Date('2024-05-05 03:22')}

Cookie Options:
a) path: It defines the virtual path. '/'
b) expires: It defines lifespan of cookie.
Note: If expires is not defined then it is temperory Cookie

Reading Cookie:

cookies.cookieName

Check Cookie Availabilty:

cookies.cookieName === undefined

Remove Cookie:

removeCookie('cookiename')

Example:

import React, { useState } from 'react'
import { useCookies } from 'react-cookie';

const UserLogin = () => {
const [userDetails, setUserDetails] = useState({ username: '', password: '' });
const [cookies, setCookie, removeCookie] = useCookies(['username']);
const handleChange = (event) => {
setUserDetails({
...userDetails,
[event.target.name]: event.target.value
})
};
const handleSubmit = (event) => {
event.preventDefault();
setCookie('username', userDetails.username ,{path: '/', expires: new Date('2024-05-05 03:22')})
// Implement logic to send userDetails to server for authentication
alert(`${JSON.stringify(userDetails)}`); // Not recommended for production
};
const handleSignOut = (event) =>{
removeCookie('username');
setUserDetails({username: '', password: ''})
}
return (
<div className='container-fluid w-25'>
<h2>User Login</h2>
<form onSubmit={handleSubmit}>
<div className="form-group m-2">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" placeholder="Enter email" name='username' onChange={handleChange} />
</div>
<div className="form-group m-2">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" placeholder="Password" name='password' onChange={handleChange} />
</div>
<button type="submit" className="btn btn-primary m-2">Submit</button>
<hr />
<h2>Hello!{cookies.username}</h2>
<hr />
<button className='btn btn-link' onClick={handleSignOut}>Sign Out</button>
</form>
</div>
)
}
export default UserLogin;
Output:

After submit:

After clicking on Sign-out button:

Thanks…

--

--