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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bhammond/react-stateful

v1.3.12

Published

A Signal and Querystate backed React State management utility library.

Downloads

1,252

Readme

@bhammond/react-stateful

Framework-agnostic URL-synchronized state management with built-in state sharing between components. Uses signals to share state efficiently between components.

Features

  • 🔄 State sharing between components using signals
  • 🌐 URL synchronization with component state
  • 🧭 Browser navigation (back/forward) support
  • 🤝 Framework agnostic design
  • 📦 TypeScript included
  • 🪶 Small bundle size (~1KB)
  • 💪 No dependencies

Installation

npm install @bhammond/react-stateful

Requirements

  • React 16.8+

Basic Usage

import { useQueryState } from '@bhammond/react-stateful';

function SearchComponent() {
  const params = new URLSearchParams(window.location.search);
  const [query, setQuery] = useQueryState('q', params);

  return (
    <input
      value={query ?? ''}
      onChange={(e) => setQuery(e.target.value)}
      placeholder="Search..."
    />
  );
}

State Sharing Between Components

Components using the same key will share state through signals:

import { useQueryState } from '@bhammond/react-stateful';

function SearchInput({ params }) {
  const [query, setQuery] = useQueryState('q', params);
  return <input value={query ?? ''} onChange={e => setQuery(e.target.value)} />;
}

function SearchResults({ params }) {
  const [query] = useQueryState('q', params);
  return <div>Results for: {query}</div>;
}

function FilterStatus({ params }) {
  const [query] = useQueryState('q', params);
  return <div>Current filter: {query || 'None'}</div>;
}

function SearchPage() {
  const params = new URLSearchParams(window.location.search);
  return (
    <div>
      <SearchInput params={params} />
      <FilterStatus params={params} />
      <SearchResults params={params} />
    </div>
  );
}

Complex Objects

The hook works with complex objects and maintains type safety:

interface Filters {
  search: string;
  category: string;
  sortBy: string;
  page: number;
}

const DEFAULT_FILTERS: Filters = {
  search: '',
  category: 'all',
  sortBy: 'date',
  page: 1
};

function FilterPanel({ params }) {
  const [filters, setFilters] = useQueryState<Filters>('filters', params, DEFAULT_FILTERS);

  const updateFilter = (key: keyof Filters, value: Filters[keyof Filters]) => {
    setFilters(current => ({
      ...current,
      [key]: value,
      page: key === 'page' ? value : 1
    }));
  };

  return (
    <div>
      <input
        value={filters.search}
        onChange={e => updateFilter('search', e.target.value)}
      />
      <select
        value={filters.category}
        onChange={e => updateFilter('category', e.target.value)}
      >
        {/* options */}
      </select>
    </div>
  );
}

API Reference

useQueryState

function useQueryState<T = string>(
  name: string,
  params: ParamsInput,
  defaultValue?: T
): [T, (newValue: T | ((prev: T) => T)) => void]

Parameters

  • name: string - URL parameter key
  • params: ParamsInput - Either:
    • URLParamsLike: An object with a get(key: string): string | null method
    • RecordParams: An object with string or string array values
  • defaultValue?: T - Optional default value when parameter is not present

Returns

  • [value, setValue] - A tuple containing the current value and setter function

Framework Integration

React Router

import { useSearchParams } from 'react-router-dom';
import { useQueryState } from '@bhammond/react-stateful';

function SearchComponent() {
  const [searchParams] = useSearchParams();
  const [query, setQuery] = useQueryState('q', searchParams);

  return (
    <input
      value={query ?? ''}
      onChange={(e) => setQuery(e.target.value)}
    />
  );
}

Custom Implementation

class CustomParams implements URLParamsLike {
  private params: Map<string, string>;

  constructor() {
    this.params = new Map();
  }

  get(key: string): string | null {
    return this.params.get(key) ?? null;
  }

  set(key: string, value: string): void {
    this.params.set(key, value);
  }
}

function Component() {
  const params = new CustomParams();
  const [value, setValue] = useQueryState('key', params);
  // ...
}

TypeScript Support

Includes TypeScript definitions with full type inference support.

Performance

  • Signal-based state sharing
  • Selective component updates
  • Batched URL updates
  • Small bundle size
  • No external dependencies

Contributing

Contributions are welcome. Please feel free to submit a Pull Request.

License

MIT