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
Quick Start
Place the Provider (once per App)
Put a "use client"
directive on the Provider:
Place it at the root of your application, in a Server Component
Setup a cookie
Use defineCookie to configure validation rules and expiration settings for the cookie.
Read and Write.
Changes to the cookie are synchronized across all instances of the hook and across browser tabs.
Validation
To ensure data integrity, cookies should be validated.
👉 Functional validation
For simple cases you can use a function to validate the cookie value.
👉 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.
Outside of React
defineCookie
returns a standalone utility object that provides methods to get
, set
or clear
the cookie outside of React components.
Using it still triggers a React re-render.
On the server
The Cookie utility can read cookies from the cookie header.
API Reference
👉 defineCookies
DefineCookieOptions
The options of the cookie.
Prop | Type | Default |
---|---|---|
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.
Props
The props of the ServerCookieProvider component.
Prop | Type | Default |
---|---|---|
children | ReactNode | - |
value | ServerCookieCtxValue | - |
👉 useCookie
Manage cookie state like with useState.
👉 Cookie
Read and write the cookie outside of React.