Docs
Cookies

Cookies

Store and retrieve from the browser’s cookie storage.

About

The useCookie hook is a custom React hook designed to manage state synchronized with cookies. It leverages the js-cookie library for cookie manipulation and provides a seamless interface for React components to work with cookie-based state. This hook is particularly useful when you need to persist state across page reloads or sessions, such as user preferences, authentication tokens, or other client-specific data.

Parameters

PropertyTypeDescriptionDefault
cookieKeystringThe key of Cookie-
optionsOptionsOptional. Cookie configuration-

Return Values

PropertyTypeDescription
statestring | undefinedLocal Cookie value
setStateSetStateUpdate Cookie value

setState can update cookie options, which will be merged with the options set by useCookieState.

const targetOptions = { ...options, ...updateOptions }

If you want to delete this record from document.cookie, use setState() or setState(undefined).

Options

PropertyDescriptionTypeDefault
defaultValueOptional. Default value, but not store to Cookiestring | undefined | (() => (string | undefined))undefined
expiresOptional. Set Cookie expiration timenumber | Date-
pathOptional. Specify available pathsstring/
domainOptional. Specify available domain. Default creation domainstring-
secureOptional. Specify whether the Cookie can only be transmitted over secure protocol as httpsbooleanfalse
sameSiteOptional. Specify whether the browser can send this Cookie along with cross-site requestsstrict | lax | none-

Options is same as js-cookie attributes.

Installation

Run the following command:

npx scriptkavi-hooks@latest add cookies

Usage

import { useCookie } from "@/hooks/cookies"
import React from "react"
 
import useCookie from "./useCookie"
 
const CookieComponent: React.FC = () => {
  const [username, setUsername] = useCookie("username", {
    defaultValue: "Guest",
    expires: 7, // Cookie will expire in 7 days
    path: "/",
    secure: true,
    sameSite: "Lax",
  })
 
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setUsername(event.target.value)
  }
 
  const handleClear = () => {
    setUsername(undefined) // This will remove the cookie
  }
 
  return (
    <div>
      <h1>Manage Cookies</h1>
      <label>
        Username:
        <input type="text" value={username} onChange={handleChange} />
      </label>
      <button onClick={handleClear}>Clear Username</button>
      <p>Current Username: {username}</p>
    </div>
  )
}
 
export default CookieComponent