useCookies

A React hook that provides an unopinionated interface for managing browser cookies with standard configuration options.

Important

When using remove(), you must provide the same path and domain options used when the cookie was originally set; otherwise, the browser will fail to delete it.

Note

This hook is purely imperative and does not sync with React state. Changing a cookie will not trigger a re-render of your components.

Installation

bash

Description

The useCookies offers a functional approach to interacting with document.cookie. It abstracts the manual string parsing and formatting required by the native API, providing dedicated methods to set, get, and remove cookies. It includes support for standard attributes such as domain, expires, maxAge, path, secure, and sameSite, while remaining SSR-safe by checking for the existence of the document object.

Return values

NameTypeDescription
get(name: string) => string | nullRetrieves the value of a specific cookie by its name.
getAll() => Record<string, string>Returns all available cookies as a key-value object.
remove(name: string, options?: UseCookieOptions) => voidDeletes a cookie by setting its max-age to 0.
set(name: string, value: string, options?: UseCookieOptions) => voidCreates or updates a cookie with the specified value and attributes.

Demo

🍪 Cookies and Privacy

We use cookies to improve your experience. You can accept or decline the use of cookies by clicking on the button below.

Source code

tsx