hooks
useCookie

useCookie

A custom hook for managing cookies.

Add hook

Create a file use-cookie.ts and copy & paste the code from useCookie.

Hook

// Original implementation
// https://github.com/tylerwolff/useCookie
 
import { useCallback, useState } from 'react'
 
type CookieOptions = {
    days?: number
    path?: string
    domain?: string
    SameSite?: 'None' | 'Lax' | 'Strict'
    Secure?: boolean
    HttpOnly?: boolean
}
 
export const useCookie = (key: string, initialValue: string) => {
    const [item, setItem] = useState(() => {
        return getCookie(key, initialValue)
    })
 
    const updateItem = useCallback(
        (value: string, options: CookieOptions) => {
            setItem(value)
            setCookie(key, value, options)
        },
        [key],
    )
 
    return [item, updateItem]
}
 
export const stringifyOptions = (options: { [key: string]: boolean | number | string | undefined }) => {
    return Object.keys(options).reduce((acc, key) => {
        if (key === 'days') {
            return acc
        } else {
            if (options[key] === false) {
                return acc
            } else if (options[key] === true) {
                return `${acc}; ${key}`
            } else {
                return `${acc}; ${key}=${options[key]}`
            }
        }
    }, '')
}
 
export const setCookie = (key: string, value: string, options: CookieOptions) => {
    const optionsWithDefaults = {
        days: 7,
        path: '/',
        ...options,
    }
 
    const expires = new Date(Date.now() + optionsWithDefaults.days * 864e5).toUTCString()
 
    document.cookie =
        key + '=' + encodeURIComponent(value) + '; expires=' + expires + stringifyOptions(optionsWithDefaults)
}
 
export const getCookie = (name: string, initialValue = '') => {
    return (
        document.cookie.split('; ').reduce((r, v) => {
            const parts = v.split('=')
            return parts[0] === name ? decodeURIComponent(parts[1]) : r
        }, '') || initialValue
    )
}
 

Usage

 
import React from 'react';
import { useCookie } from './use-cookie';
 
function App() {
    const [userToken, setUserToken] = useCookie('token', '');
 
    const handleLogin = (token: string) => {
        setUserToken(token, { days: 7, path: '/', SameSite: 'Strict', Secure: true });
    };
 
    return (
        <div>
            <h1>useCookie Example</h1>
            <p>Token: {userToken}</p>
            <button onClick={() => handleLogin('newTokenValue')}>Login</button>
        </div>
    );
}
 
export default App;
 

API

Parameters

NameTypeDescription
keystringThe name of the cookie.
initialValuestringThe initial value of the cookie if it doesn't exist.

Returns

NameTypeDescription
itemstringThe current value of the cookie.
updateItem(value: string, options: CookieOptions) => voidA function to update the cookie's value and options.

Contributors

Avatar 1