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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@syncraft-labs/react

v0.2.0

Published

React hooks for Syncraft Labs — local-first state synchronization.

Downloads

329

Readme

@syncraft-labs/react

React hooks for Syncraft Labs — local-first state synchronization.

npm version License: MIT TypeScript

@syncraft-labs/react provides the useSync hook — a single hook that gives your React components instant writes, IndexedDB persistence, background sync, and offline support.

Built on useSyncExternalStore for tear-free concurrent rendering.

Install

npm install @syncraft-labs/core @syncraft-labs/react

Peer dependencies: React ≥ 18.0.0

Quick Start

import { useSync } from "@syncraft-labs/react";

interface TodoState {
  todos: Array<{ id: string; text: string; done: boolean }>;
}

function TodoApp() {
  const { data, update, isHydrating, isOffline, error } = useSync<TodoState>(
    "todos",
    {
      initialState: { todos: [] },
    },
  );

  if (isHydrating) return <p>Loading from cache…</p>;

  return (
    <div>
      {isOffline && <p>You're offline — changes saved locally</p>}
      {error && <p>Error: {error.message}</p>}

      <button
        onClick={() =>
          update((draft) => {
            draft.todos.push({
              id: crypto.randomUUID(),
              text: "New todo",
              done: false,
            });
          })
        }
      >
        Add Todo
      </button>

      <ul>
        {data?.todos.map((t) => (
          <li key={t.id}>
            <label>
              <input
                type="checkbox"
                checked={t.done}
                onChange={() =>
                  update((draft) => {
                    const todo = draft.todos.find((x) => x.id === t.id);
                    if (todo) todo.done = !todo.done;
                  })
                }
              />
              {t.text}
            </label>
          </li>
        ))}
      </ul>
    </div>
  );
}

With Remote Sync

const { data, update, refetch, isSyncing } = useSync<TodoState>("todos", {
  initialState: { todos: [] },

  // Fetch initial data from server (called once if IndexedDB is empty)
  fetcher: () => fetch("/api/todos").then((r) => r.json()),

  // Push pending mutations in background (automatic, with exponential backoff)
  pusher: async (entries) => {
    await fetch("/api/sync", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(entries),
    });
  },

  // Sync interval in ms (default: 5000)
  syncInterval: 3000,
});

// Pull-to-refresh
<button onClick={() => refetch()} disabled={isSyncing}>
  {isSyncing ? "Syncing…" : "Refresh"}
</button>

API

useSync<T>(key, options): UseSyncReturn<T>

| Parameter | Type | Description | |-----------|------|-------------| | key | string | Unique IndexedDB storage key | | options | UseSyncOptions<T> | Configuration object |

UseSyncOptions<T>

| Property | Type | Default | Description | |----------|------|---------|-------------| | initialState | T | undefined | Default state when IndexedDB is empty | | fetcher | () => Promise<T> | undefined | Fetch initial data from remote source | | pusher | (entries: OutboxEntry<T>[]) => Promise<void> | undefined | Push pending mutations to server | | syncInterval | number | 5000 | Background sync interval (ms) |

UseSyncReturn<T>

| Property | Type | Description | |----------|------|-------------| | data | T \| undefined | Current state (undefined during hydration) | | update | (updater: DraftUpdater<T>) => void | Mutate state with Immer draft (fire-and-forget) | | refetch | () => Promise<void> | Pull fresh data via fetcher | | isHydrating | boolean | true while loading from IndexedDB | | isSyncing | boolean | true while pusher/refetch is running | | isOffline | boolean | true when navigator.onLine is false | | error | Error \| null | Last error from set/pusher/refetch | | destroyStore | () => void | Destroy the singleton store for this key |

destroyStore(key: string): void

Destroy a store and remove it from the singleton registry. Closes the IndexedDB connection and clears all listeners.

Key Behaviors

Singleton Stores

Multiple components calling useSync("todos") share the same store instance. This ensures:

  • Consistent state across the component tree
  • Single IndexedDB connection per key
  • Shared outbox queue

Optimistic Updates

update() modifies the UI instantly. The change persists to IndexedDB in the background. If persistence fails, the update is automatically rolled back.

Background Sync

When pusher is provided, a background loop runs every syncInterval ms:

  1. Reads pending outbox entries
  2. Calls pusher(entries)
  3. Clears synced entries from outbox
  4. On failure: exponential backoff (1s → 2s → 4s → … → 60s max)
  5. On reconnect: immediate sync attempt

Network Tracking

isOffline automatically tracks navigator.onLine. When the device comes back online, the sync loop is triggered immediately (no waiting for the next interval).

License

MIT © Denis Listiadi