v1.1.0 · MIT · ~1.1 kB gzipped

Zustand CRUD in one line

Zenty is a small TypeScript library for Zustand. You define the type, Zenty gives you the store: add, update, delete, find, bulk operations, plus loading and error state. Works with React 18, React 19 and Next.js.

products.ts
1import { createEntitiesStore } from 'zenty' 2 3type Product = { id: string; name: string; price?: number } 4 5export const useProducts = createEntitiesStore<Product>() 6 7// anywhere in your app 8useProducts.getState().add({ id: 'p1', name: 'Lamp' })
  • 1 line per store
  • Fully typed
  • Loading & error included
Read the docs
Products Example Store
This is a real Zenty store running in your browser. Add a few products, edit one, delete one. Then try adding a product with an ID that already exists, or updating or deleting an ID that doesn't, and watch the error field in the live state panel. Those checks are built in.
Not LoadedReady
Live Zustand Store State
Last call: replaceAll([4 sample products])
{
  "entities": [],
  "loaded": false,
  "loading": false,
  "error": null
}
Current Products (0)
More actions

No products yet. Add some products to see them here!

Get Started with Zenty
Install and start using Zenty in your project

npm

1npm install zenty zustand

yarn

1yarn add zenty zustand

pnpm

1pnpm add zenty zustand

Same store, written twice

On the left is a hand-written Zustand store for a product list. It behaves exactly like Zenty's defaults, including the duplicate and missing-ID errors. Not more, not less. On the right is the Zenty version.

Without Zenty · 113 lines
import { create } from 'zustand'

type Product = {
  id: string
  name: string
  price?: number
  category?: string
}

type ProductState = {
  entities: Product[]
  loaded: boolean
  loading: boolean
  error: string | null
}

type ProductActions = {
  add: (item: Product) => void
  addMany: (items: Product[]) => void
  update: (id: string, patch: Partial<Product>) => void
  updateMany: (patches: (Pick<Product, 'id'> & Partial<Product>)[]) => void
  delete: (id: string) => void
  deleteMany: (ids: string[]) => void
  find: (id: string) => Product | undefined
  has: (id: string) => boolean
  clear: () => void
  replaceAll: (items: Product[]) => void
  setLoading: (loading: boolean) => void
  setError: (error: string | null) => void
}

export const useProductStore = create<ProductState & ProductActions>()((set, get) => ({
  entities: [],
  loaded: false,
  loading: false,
  error: null,

  add: (item) =>
    set((state) =>
      state.entities.some((e) => e.id === item.id)
        ? { loaded: true, loading: false, error: `Item with id=${item.id} already exists.` }
        : { entities: [...state.entities, item], loaded: true, loading: false, error: null }
    ),

  addMany: (items) =>
    set((state) => {
      const seen = new Set(state.entities.map((e) => e.id))
      const duplicates = new Set<string>()
      for (const item of items) {
        if (seen.has(item.id)) duplicates.add(item.id)
        seen.add(item.id)
      }
      if (duplicates.size > 0) {
        const ids = [...duplicates].join(', ')
        return { loaded: true, loading: false, error: `Items with id=${ids} already exist.` }
      }
      return { entities: [...state.entities, ...items], loaded: true, loading: false, error: null }
    }),

  update: (id, patch) =>
    set((state) => {
      if (!state.entities.some((e) => e.id === id)) {
        return { loading: false, error: `Item with id=${id} was not found.` }
      }
      if ('id' in patch && patch.id !== id && state.entities.some((e) => e.id === patch.id)) {
        return {
          loading: false,
          error: `Cannot change id=${id} to ${patch.id}: an item with that id already exists.`,
        }
      }
      return {
        entities: state.entities.map((e) => (e.id === id ? { ...e, ...patch } : e)),
        loading: false,
        error: null,
      }
    }),

  updateMany: (patches) =>
    set((state) => ({
      entities: state.entities.map((e) => {
        const p = patches.find((x) => x.id === e.id)
        return p ? { ...e, ...p } : e
      }),
      loading: false,
      error: null,
    })),

  delete: (id) =>
    set((state) =>
      state.entities.some((e) => e.id === id)
        ? { entities: state.entities.filter((e) => e.id !== id), loading: false, error: null }
        : { loading: false, error: `Item with id=${id} was not found.` }
    ),

  deleteMany: (ids) =>
    set((state) => ({
      entities: state.entities.filter((e) => !ids.includes(e.id)),
      loading: false,
      error: null,
    })),

  find: (id) => get().entities.find((e) => e.id === id),

  has: (id) => get().entities.some((e) => e.id === id),

  clear: () => set({ entities: [], loaded: false, loading: false, error: null }),

  replaceAll: (items) => set({ entities: items, loaded: true, loading: false, error: null }),

  setLoading: (loading) => set({ loading }),

  setError: (error) => set(error === null ? { error } : { error, loading: false }),
}))
With Zenty · 1 line
import { createEntitiesStore } from 'zenty'

type Product = {
  id: string
  name: string
  price?: number
  category?: string
}

export const useProductStore = createEntitiesStore<Product>()

What you get

For lists (createEntitiesStore)

add, addMany, update, updateMany, delete, deleteMany, find, has, replaceAll and clear. Plus entities, loaded, loading and error. IDs stay unique: duplicates, missing IDs and ID collisions set error, and every write ends loading.

For single objects (createEntityStore)

set, update and clear. Turn on deepMerge and nested updates keep the fields you didn't touch.

Your own ID field

Not every API calls it id. Pass idKey: 'userId' and everything is typed against that key.

Zustand middleware

Pass persist, devtools or your own middleware through middleware. Options like partialize are typed against the store.

Override any action

Want new items sorted by name? Pass your own add. The rest stays default.

What Zenty doesn't do

It doesn't fetch, cache or refetch data, and it has no selection state. For server data with caching and refetching, TanStack Query is the better fit. Zustand middleware like persist and devtools plugs in through the middleware option.

Zenty FAQ

Short answers. The docs have the details.

Frequently asked questions

What is Zenty?

Zenty is an open-source TypeScript library that adds CRUD to Zustand. createEntitiesStore gives you a typed store for a list, createEntityStore one for a single object. Both come with loading, loaded and error. It's MIT-licensed and about 1.1 kB gzipped.

Is Zenty a replacement for Zustand?

No. Zenty calls Zustand's create() under the hood and hands you a normal Zustand hook. You still install Zustand, and your existing stores keep working next to the Zenty ones. So you can move one store at a time, or just use Zenty for new ones.

How do I install Zenty?

npm install zenty zustand

Zenty works with Zustand 4.4+ and 5, and React 18 or 19.

How do I manage a list?

Start with:

const useProducts = createEntitiesStore<Product>()

If your type has an id field, that's it. If the ID is called something else, pass idKey, e.g. createEntitiesStore<User, 'userId'>({ idKey: 'userId' }). IDs stay unique: add and addMany refuse IDs that already exist (a rejected addMany adds nothing), update refuses to change an ID to one that is taken, and update or delete on a missing ID sets error instead of failing silently.

How do I manage a single object, like settings or the current user?

Use createEntityStore with deepMerge on:

const useSettings = createEntityStore<Settings>({ deepMerge: true })

set replaces the object, update merges into it, clear resets it to null. With deepMerge: true, nested objects are merged instead of overwritten, and update is typed as DeepPartial<T>, so nested partials need no cast. Dates, arrays and Maps are replaced as whole values. Calling update before set sets error.

How do I load data from an API?

Zenty doesn't fetch for you. You call your API and put the result into the store:

const { setLoading, setError, replaceAll } = useProducts.getState()
setLoading(true)
try {
  const res = await fetch('/api/products')
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  replaceAll(await res.json())
} catch {
  setError('Could not load products')
}

No finally needed: every write (replaceAll, add, update, …) and setError('…') end loading. setError(null) keeps it, so you can clear an old error at the start of a request.

Does Zenty work with Next.js?

Yes, in client components ('use client'). A Zenty store is a regular module-level Zustand store, so the usual Zustand advice for Next.js applies. Don't keep per-user data in it during server rendering.

Does Zenty work with persist or devtools?

Yes. Pass any Zustand middleware through the middleware option:

import { devtools, persist } from 'zustand/middleware'

const useProducts = createEntitiesStore<Product>({
  middleware: (config) =>
    devtools(persist(config, { name: 'products', partialize: (s) => ({ entities: s.entities, loaded: s.loaded }) })),
})

It's fully typed, so partialize sees the real store state. Persist loaded together with your data, otherwise it comes from initialState on every page load.

Zenty or TanStack Query?

Different jobs. TanStack Query caches server data and handles refetching, stale data and invalidation. Zenty is a plain client store you control yourself. It fits when you want the data in Zustand anyway: local edits before saving, a list fed by a WebSocket or a Firestore listener, or an admin table you update by hand. Plenty of apps use both.

Zenty or Redux Toolkit?

If you're already on Zustand, adding Redux for CRUD is a lot of setup for little gain. Redux Toolkit is a full framework with slices, middleware, devtools and RTK Query. Zenty does one thing: the CRUD part of a Zustand store. Zustand's devtools middleware plugs into Zenty and works with the Redux DevTools extension. For a full framework with RTK Query and listener middleware, RTK is the bigger toolbox.

Zenty compared

For CRUD state in a React app.

Scroll horizontally to see all columns.

CriteriaZentyZustand, hand-writtenRedux ToolkitContext + useReducer
Code for a list store1 line113 lines (see above)slice + store setupreducer + provider
Typed actionsinferred from your typeyou write the typesyesyou write the types
Loading / error stateincludedyou write itvia thunks or RTK Queryyou write it
Data fetching & cachingnonoyes (RTK Query)no
Devtools / middlewareyes (middleware option)yesyesno
Good fit forCRUD lists and objects in Zustand appscustom store logiclarge apps, complex flowssmall, local state