one-hook
Size
1.10 kb
View source

useCookie

A simple typesafe state manager using cookies.

Features

  • Avoid Layout Shifts: The state is known by both the client and the server.
  • Built-in Validation: Validate with zod, valibot, arktype or with a simple function.
  • Tab Sync: The cookie state is synced across multiple browser tabs.
  • Component Sync: The cookie state is synced across all components.
  • Fullstack: Includes server-side utilities for end-to-end type safety.

Installation

npm install @1hook/use-cookie

Quick Start

Place the Provider (once per App)

Put a "use client" directive on the Provider:

cookie-provider.tsx
'use client'
export {  } from '@1hook/use-cookie'

Place it at the root of your application, in a Server Component

providers.tsx
import {  } from 'next/headers'
import {  } from './cookie-provider'

export async function (: { :  }) {
  return (
    < ={(await ()).('cookie')}>
      {.}
    </>
  )
}

Use defineCookie to configure validation rules and expiration settings for the cookie.

sidebar-width.ts
import {  } from 'zod'
import {  } from '@1hook/use-cookie'

export const [] = ({
  : 'sidebar-width',
  : .().(200),
  : 365, // days from now
  : 'lax',
})

Read and Write.

Changes to the cookie are synchronized across all instances of the hook and across browser tabs.

layout.tsx
function () {
  const [, ] = ()

  return (
    <>
      < ={} ={} />
      <>...</>
    </>
  )
}

Validation

To ensure data integrity, cookies should be validated.

👉 Functional validation

For simple cases you can use a function to validate the cookie value.

({
  : 'search',
  : () => ( ?? ''),
})

👉 Schema validation

For more complex cases you can use a schema to validate the cookie value. Compatible validation libraries include zod 3.24+, valibot 1.0+ or arktype 2.0+. Check out Standard Schema for more info.

import {  } from 'zod'

({
  : 'search',
  : .().(''),
})

Outside of React

defineCookie returns a standalone utility object that provides methods to get, set or clear the cookie outside of React components.

export const [, ] = ({
  : 'my-cookie',
  : .().(),
  : 7,
})

Using it still triggers a React re-render.

import {  } from './cookie'

// Write
.('new-value')

// Read
.()

// Clear
.()

On the server

The Cookie utility can read cookies from the cookie header.

const  = (await ()).('cookie')

const  = Cookies.get()

API Reference

👉 defineCookies

function defineCookie(options: DefineCookieOptions): [useCookie, Cookie]

DefineCookieOptions

The options of the cookie.

PropTypeDefault
deserialize?
((value: string) => any)
-
serialize?
((value: unknown) => string)
-
disableEncoding?
boolean
-
secure?
boolean
-
sameSite?
"lax" | "strict" | "none"
-
expires?
number | Date
-
domain?
string
-
validate
TValidator
-
name
string
-

👉 ServerCookieProvider

You can skip this component when building Single Page Applications (SPA).

In SSR frameworks it should be rendered at the top of the component tree, and must be used within a server component.

function CookieProvider(props: Props): ReactNode

Props

The props of the ServerCookieProvider component.

PropTypeDefault
children
ReactNode
-
value
ServerCookieCtxValue
-

👉 useCookie

Manage cookie state like with useState.

function useCookie(): [state, setState]

Read and write the cookie outside of React.

On this page