npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

cookie-state

v0.0.8

Published

A minimal React library for state management using cookies

Readme

Cookie State

Demo TypeScript React License: MIT

A minimal React library for state management using cookies with full TypeScript support.

🚀 Live Demo

Try the interactive demo to see the library in action with real cookie storage, TypeScript support, and cross-domain functionality.

Installation

npm install cookie-state

Usage

💡 See it in action: Check out the live demo with interactive examples!

import { useCookieState, type CookieOptions } from 'cookie-state'

// TypeScript interface for your data
interface UserPreferences {
  theme: 'light' | 'dark'
  language: 'en' | 'es'
  notifications: boolean
}

function MyComponent() {
  // Simple counter with TypeScript support
  const { value: count, setValue: setCount, deleteValue: removeCount } = useCookieState<number>('count', 0, {
    domain: '.example.com', // required: domain for cookie sharing
    days: 7, // expires in 7 days
    path: '/',
    sameSite: 'lax'
  })

  // Complex object with TypeScript support  
  const { value: preferences, setValue: setPreferences } = useCookieState<UserPreferences>('user_prefs', {
    theme: 'light',
    language: 'en', 
    notifications: true
  }, {
    domain: '.example.com', // required domain
    days: 365
  })

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
      <button onClick={() => setCount(prev => prev - 1)}>Decrement</button>
      <button onClick={removeCount}>Reset</button>
      
      <p>Theme: {preferences.theme}</p>
      <button onClick={() => setPreferences(prev => ({ 
        ...prev, 
        theme: prev.theme === 'light' ? 'dark' : 'light' 
      }))}>
        Toggle Theme
      </button>
    </div>
  )
}

API

useCookieState<T>(cookieName, defaultValue, cookieOptions?)

  • cookieName: string - The cookie name
  • defaultValue: T - Default value if cookie doesn't exist or parsing fails
  • cookieOptions: CookieOptions - Cookie configuration options

Returns: UseCookieStateResult<T>

interface UseCookieStateResult<T> {
  value: T                                    // Current cookie value
  getValue: () => T                           // Get current value (with error handling)
  setValue: (updateFunction: (prev: T) => T) => void  // Update cookie (function-only)
  deleteValue: () => void                     // Delete the cookie
  error: boolean                              // Whether an error occurred
  errorMessage: string | null                 // Error message if any
}

Cookie Options

interface CookieOptions {
  domain: string                         // Required: Cookie domain for sharing across subdomains
  days?: number                          // Expiration in days (default: 365)
  path?: string                          // Cookie path (default: '/')
  secure?: boolean                       // Secure flag (default: auto-detect based on protocol)
  sameSite?: 'strict' | 'lax' | 'none'   // SameSite attribute (default: 'lax')
}

Key Features

  • 🔒 Type Safe: Full TypeScript support with generic types
  • 🍪 Cross-Domain: Smart cookie sharing that preserves existing values across subdomains
  • ⚡ Function-Only Updates: Safe state updates that prevent accidental overwrites
  • 🛡️ Error Handling: Built-in error detection and reporting
  • 🔄 SSR Compatible: Safe for server-side rendering environments

🌐 Cross-Domain Behavior

The library intelligently handles cookies across subdomains:

// On app.example.com - First to set the cookie
const { value } = useCookieState('user_prefs', { theme: 'light' }, { domain: '.example.com' })
// Creates cookie with: { theme: 'light' }

// On admin.example.com - Reuses existing cookie
const { value } = useCookieState('user_prefs', { theme: 'dark' }, { domain: '.example.com' }) 
// Gets existing value: { theme: 'light' } (NOT the default { theme: 'dark' })

✅ Smart Cookie Reuse:

  • Existing cookie: Uses the current value (ignores default)
  • No cookie: Sets default value for all subdomains to share
  • Parse error: Resets to default value and saves to cookie

Development

# Install dependencies
npm install

# Start development server
npm run dev

# Build demo app 
npm run build

# Build library for npm
npm run build:lib

# Preview built demo
npm run preview

🔗 Links

License

MIT