Skip to content
Zenty

Zustand and CRUD

A focused CRUD layer for Zustand.

Typed stores for lists and single objects: add, update, delete, bulk actions, plus loading, loaded and error state. Underneath, it's a regular Zustand store.

  • Type-safe
  • Zustand-native
  • ~1.1 kB gzipped
import { createEntitiesStore } from 'zenty'

type User = { id: string; name: string; email: string }

export const useUsers = createEntitiesStore<User>()

// Typed CRUD API
const { add, update, delete: remove } = useUsers.getState()
add({ id: 'u1', name: 'Lena Anders', email: 'lena@example.com' })
update('u1', { email: 'lena.anders@example.com' })
remove('u1')

Live demo

Try it in the browser.

Three real Zenty stores running on this page. Add, edit and delete rows, then look at the state each call leaves behind. The sample data stays in your browser.

Users

3 items
AvatarNameEmailActions
Lena Anderslena@example.com
Max Kleinmax@example.com
Jonas Petersjonas@example.com

Every action below is a real Zenty call.

Less boilerplate

The same result. A lot less code.

A product store written with Zustand alone needs twelve actions, loading and error state, and checks for duplicate and missing IDs. The Zenty version behaves the same way.

Counted: non-empty lines shown in each panel. Both files also need the same import and the same Product type, so those are left out of both.

Without Zenty (Zustand only)90 lines
products.ts
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
products.ts
export const useProductStore = createEntitiesStore<Product>()

All twelve actions and the state fields, typed from Product.

1 line

Two stores

One helper for lists, one for single objects.

Both return a normal Zustand hook. Selectors, getState(), subscribe and middleware work the way you know them.

For a list createEntitiesStore

products.ts
const useProducts = createEntitiesStore<Product>()
Actions
  • add
  • addMany
  • update
  • updateMany
  • delete
  • deleteMany
  • find
  • has
  • replaceAll
  • clear
  • setLoading
  • setError
State
  • entities
  • loaded
  • loading
  • error
Built-in rules
  • IDs stay unique. A duplicate or an ID collision sets error and adds nothing.
  • update or delete on a missing ID sets error instead of failing silently.
  • Every write ends loading, so you don't need a finally block.
Options
idKey for IDs not called id, initialState, your own version of any action, Zustand middleware.
createEntitiesStore API reference

For a single object createEntityStore

settings.ts
const useSettings = createEntityStore<Settings>({ deepMerge: true })
Actions
  • set
  • update
  • clear
  • setLoading
  • setError
State
  • entity
  • loaded
  • loading
  • error
Built-in rules
  • set replaces the object, update merges into it, clear resets it to null.
  • With deepMerge, nested objects merge too and update takes a DeepPartial.
  • update before set sets error. Dates, arrays and Maps are replaced whole.
Options
initialState, deepMerge, Zustand middleware.
createEntityStore API reference

Fit

When Zenty is the right tool, and when it isn't.

Zenty does one job: the CRUD part of a Zustand store. Find your situation below.

Get started

Three steps to your first store.

  1. Install Zenty next to Zustand

    Zustand and React are peer dependencies.

    terminal
    npm install zenty zustand
  2. Create a store from your type

    If the type has an id field, that's all the setup.

    stores/products.ts
    import { createEntitiesStore } from 'zenty'
    
    type Product = { id: string; name: string; price?: number }
    
    export const useProducts = createEntitiesStore<Product>()
  3. Use it in a component

    It's a Zustand hook, so selectors work as usual.

    components/product-list.tsx
    'use client'
    import { useProducts } from '@/stores/products'
    
    export function ProductList() {
      const { entities, loading, error, add } = useProducts()
    
      if (loading) return <p>Loading…</p>
      if (error) return <p role="alert">{error}</p>
    
      return (
        <>
          <ul>
            {entities.map((p) => <li key={p.id}>{p.name}</li>)}
          </ul>
          <button onClick={() => add({ id: crypto.randomUUID(), name: 'New product' })}>
            Add product
          </button>
        </>
      )
    }

Next: the docs cover custom IDs, your own actions, deep merge, middleware and async patterns.

FAQ

Questions developers ask.

Short answers. The docs have the details.

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?

Shell
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:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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.

Start with one store.

Move one hand-written list to Zenty and keep the rest of your Zustand stores as they are.

npm install zenty zustand
Read the quick start