Skip to content

useRepository

What this solves

When using dependency injection, components need a way to access repositories without:

  • Direct imports that create tight coupling
  • Circular dependency issues during HMR
  • Losing type safety

useRepository provides type-safe access to DI-registered repositories through React context.


When to use it

Use this hook when:

  • You're using Katalyst's DI architecture
  • You need to access a repository from a React component
  • You want testable, loosely-coupled data access

When NOT to use it

  • If you're not using DI — import repositories directly
  • For simple projects — direct imports are simpler
  • In non-React code — use the container directly

Basic usage

tsx
import { useRepository } from '@/shared/hooks'
import type { IUserRepository } from '@/modules/management/users/domain'
import { USER_SYMBOLS } from '@/modules/management/users/di/symbols'

export function UserList() {
  const userRepository = useRepository<IUserRepository>(USER_SYMBOLS.IUserRepository)

  // Use with React Query
  const { data: users } = useQuery({
    queryKey: ['users'],
    queryFn: () => userRepository.getAll(),
  })

  return <ul>{users?.map(u => <li key={u.id}>{u.name}</li>)}</ul>
}

Create module-specific wrapper hooks for better ergonomics:

tsx
// modules/management/users/application/hooks/useUsersRepository.ts
import { useRepository } from '@/shared/hooks'
import type { IUserRepository } from '../domain'
import { USER_SYMBOLS } from '../di/symbols'

export const useUsersRepository = () =>
  useRepository<IUserRepository>(USER_SYMBOLS.IUserRepository)

Then use the wrapper:

tsx
import { useUsersRepository } from '@/modules/management/users/application/hooks'

export function UserList() {
  const userRepository = useUsersRepository()
  // ...
}

API reference (concise)

ts
function useRepository<T>(symbol: symbol): T
ParameterTypeDescription
symbolsymbolThe DI symbol for the repository

Returns: The repository instance of type T.


Notes

  • Requires the DIProvider to be mounted (included in AppProviders)
  • The repository instance is memoized to prevent unnecessary re-renders
  • Uses React context internally to avoid HMR circular dependency issues
  • This hook is part of Katalyst's optional DI architecture