Skip to content
Zenty

Migrating from a hand-written store

Move an existing Zustand CRUD store to Zenty one store at a time: what changes in the store and in your components.

Applies to zenty v1.1.0

A typical hand-written Zustand store keeps a list, a loading flag, an error and a few actions. Zenty replaces that store, and the rest of your app barely changes. You can move one store at a time.

Before(link to this section)

A store like this, with its own state type and three actions:

stores/products.ts
import { create } from 'zustand'

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

type ProductState = {
  products: Product[]
  loading: boolean
  error: string | null
  addProduct: (product: Product) => void
  updateProduct: (id: string, updates: Partial<Product>) => void
  deleteProduct: (id: string) => void
}

const useProductStore = create<ProductState>()((set) => ({
  products: [],
  loading: false,
  error: null,
  addProduct: (product) => set((state) => ({
    products: [...state.products, product]
  })),
  updateProduct: (id, updates) => set((state) => ({
    products: state.products.map(p => 
      p.id === id ? { ...p, ...updates } : p
    )
  })),
  deleteProduct: (id) => set((state) => ({
    products: state.products.filter(p => p.id !== id)
  })),
}))

After(link to this section)

stores/products.ts
import { createEntitiesStore } from 'zenty'

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

const useProductStore = createEntitiesStore<Product>()

The Zenty store has everything the old one had, plus:

  • addMany, updateMany, deleteMany, replaceAll, clear, find and has.
  • A loaded flag, and loading that ends on every write.
  • Errors for duplicate and missing IDs, see built-in errors.

Update your components(link to this section)

The list is called entities and the actions have short names. Rename them while destructuring and the component code stays the same:

components/product-list.tsx
// Before
const { products, addProduct, loading } = useProductStore()

// After: same names in your component, mapped from Zenty's actions
const { entities: products, add: addProduct, loading } = useProductStore()

One store at a time(link to this section)

Zenty stores are regular Zustand stores, so they work next to the ones you already have. Move one list, check the screens that use it, and continue when you're happy with the result.

Found a mistake? Open an issue.