@void-snippets/react

createResourceHooks

Factory that creates four TanStack Query hooks for a resource.

#What it does

The main factory. Pass your ResourceService instance and a cache key prefix, and it returns four fully typed TanStack Query hooks. All types flow from your service definition — you never write a generic at the call site.

typescript
function createResourceHooks<K extends string, S extends ResourceService>(
  queryKeyPrefix: K,
  apiService:     S,
  options?:       VSResourceHooksOptions,
): { useList, useGet, useMutations, useInfinite }

#Arguments

ArgumentTypeDescription
queryKeyPrefixstringTanStack Query cache namespace. Use the resource name: 'contacts', 'users'.
apiServiceResourceService subclassYour service instance. All hook types are inferred from this.
optionsVSResourceHooksOptions (optional)Adapters, default pagination, and optimistic update handlers.

#VSResourceHooksOptions

typescript
interface VSResourceHooksOptions {
  adapters?:      VSAdapters;           // custom adapter if your API shape differs
  defaultParams?: VSQueryParams;        // default { page, limit } (default: { page: 1, limit: 10 })
  optimistic?:    VSOptimisticHandlers; // cache transform functions for instant UI updates
}

#Examples

typescript
// contacts/contacts.hooks.ts

// Minimal — works if your API matches the default response shape
export const contactHooks = createResourceHooks('contacts', ContactsApis);

// With custom defaults and optimistic updates
export const contactHooks = createResourceHooks('contacts', ContactsApis, {
  defaultParams: { page: 1, limit: 25 },
  optimistic: {
    remove: (cache, id) => cache.filter(c => c._id !== id),
    update: (cache, { _id, payload }) =>
      cache.map(c => c._id === _id ? { ...c, ...payload } : c),
  },
});