Skip to main content

Documentation Index

Fetch the complete documentation index at: https://grantmaster.dev/llms.txt

Use this file to discover all available pages before exploring further.

Hooks Reference

Shared custom React hooks used across the GrantMaster application. Each hook encapsulates data fetching, mutation, and state management for a specific domain.

Quick Index

All hooks live in src/hooks/ unless noted as context hooks.
HookSourcePurpose
useZodFormsrc/hooks/useZodForm.tsStandardized form handling (react-hook-form + Zod)
useProjectssrc/hooks/useProjects.tsProject CRUD with optimistic updates
useIntegrationssrc/hooks/useIntegrations.tsIntegration surface (exports, API keys, webhooks)
useGrantorssrc/hooks/useGrantors.tsGrantor taxonomy CRUD
useKeyboardShortcutssrc/hooks/useKeyboardShortcuts.tsGlobal keyboard shortcut registration
useIntelligencesrc/hooks/useIntelligence.tsIntelligence module (benchmarks, funder data, trends)
useJournalssrc/hooks/useJournals.tsJournal/journal entries
useJournalSubmissionssrc/hooks/useJournalSubmissions.tsMonthly journal submissions
useCompliancesrc/hooks/useCompliance.tsCompliance monitoring
useAuditLogsrc/hooks/useAuditLog.tsAudit log querying
useUserManagementsrc/hooks/useUserManagement.tsTeam/user management
useUserssrc/hooks/useUsers.tsUser data fetching
useSubscriptionLimitssrc/hooks/useSubscriptionLimits.tsSubscription tier/quota checks
useSettingssrc/hooks/useSettings.tsOrganization settings
usePartnerPermissionssrc/hooks/usePartnerPermissions.tsPartner portal permission checks
useWidgetssrc/hooks/useWidgets.tsWidget system
useWidgetDashboardsrc/hooks/useWidgetDashboard.tsDashboard widget layout
useConfirmDialogsrc/hooks/useConfirmDialog.tsxConfirm dialog state
useUnsavedChangessrc/hooks/useUnsavedChanges.tsxUnsaved changes prompt
useDataFetchsrc/hooks/useDataFetch.tsGeneric async data fetching
useAsyncActionsrc/hooks/useAsyncAction.tsAsync action with loading/error state
useOptimisticUpdatesrc/hooks/useOptimisticUpdate.tsOptimistic update pattern
usePaginatedDatasrc/hooks/usePaginatedData.tsPaginated Firestore queries
useFirestoreListenersrc/hooks/useFirestoreListener.tsReal-time Firestore subscription
useBackupOperationssrc/hooks/useBackupOperations.tsBackup/restore job management and restore request approval
useTablePreferencessrc/hooks/useTablePreferences.tsTable column/sort preferences
useNetworkStatussrc/hooks/useNetworkStatus.tsOnline/offline detection
useSessionTimeoutsrc/hooks/useSessionTimeout.tsxSession idle timeout
useErrorHandlersrc/hooks/useErrorHandler.tsError boundary helper
useI18nsrc/hooks/useI18n.tsi18n utilities
useTRPCsrc/hooks/useTRPC.tstRPC client helper
useAccessibilitysrc/hooks/useAccessibility.tsAccessibility utilities
usePlatformFaviconsrc/hooks/usePlatformFavicon.tsDynamic favicon
useTouchGesturessrc/hooks/useTouchGestures.tsMobile touch gestures
useShareImpactTriggersrc/hooks/useShareImpactTrigger.tsImpact sharing triggers
useGrantorComplianceSyncsrc/hooks/useGrantorComplianceSync.tsGrantor compliance sync
Feature-level hooks (from src/features/*/hooks/):
HookSourcePurpose
useAgentRunsfeatures/agents/hooks/useAgentRuns.tsAgent run list with filtering and computed summary stats (totalRuns, creditsConsumed, etc.)
useGrantAssistantStatefeatures/ai/hooks/useGrantAssistantState.tsGrant Assistant panel UI state (open/close, input, loading, scroll)
useAuditDashboardfeatures/auditor/hooks/useAuditDashboard.tsAuditor dashboard summary and refresh state
useAuditorReviewPanelfeatures/auditor/components/AuditorReviewPanel/AuditorReviewPanelContext.tsxAuditor review panel selection and actions
useCompliancefeatures/compliance/ComplianceContext.tsxProject compliance workflow compatibility hook
useCurrentFolderDocumentsfeatures/documents/DocumentBrainContext.tsxCurrent folder document list for Document Brain
useDocumentBrainPageStatefeatures/documents/hooks/useDocumentBrainPageState.tsDocument Brain page orchestration state
useDashboardTemplateEditorfeatures/dashboard/components/DashboardTemplateEditor/DashboardTemplateEditorContext.tsxDashboard template editor context state
useDashboardTemplateEditorModalStatefeatures/dashboard/hooks/useDashboardTemplateEditorModalState.tsDashboard template modal open/close state
useDocumentBrainfeatures/documents/DocumentBrainContext.tsxDocument Brain data/actions compatibility hook
useDocumentStatsfeatures/documents/DocumentBrainContext.tsxDocument Brain derived stats
useEmailManagementfeatures/email/components/EmailManagement/EmailManagementContext.tsxEmail management data/actions
useExpensesfeatures/expenses/hooks/useExpenses.tsExpense list and mutation API
useMarketplacefeatures/extensions/hooks/useExtensions.tsExtension marketplace listings and actions
useActiveGrantfeatures/grants/GrantContext.tsxSelect a single active grant from grants data
useActiveGrantsListfeatures/grants/hooks/useGrants.tsQuery-backed active grants list
useGrantfeatures/grants/hooks/useGrants.tsQuery-backed single grant lookup
useGrantApplicationsListfeatures/grants/hooks/useGrants.tsQuery-backed grant applications list
useGrantMutationsfeatures/grants/hooks/useGrants.tsCanonical grant mutation surface
useGrantOperatingSnapshotfeatures/grants/useGrantOperatingSnapshot.tsCross-domain grant operating snapshot data
useGrantOpportunityfeatures/grants/GrantContext.tsxSelect a single opportunity from grants data
useGrantOpportunitiesListfeatures/grants/hooks/useGrants.tsQuery-backed grant opportunities list
useGrantorAnalyticsfeatures/grantors/hooks/useGrantorAnalytics.tsGrantor analytics and portfolio metrics
useGrantorInteractionsfeatures/grantors/hooks/useGrantorInteractions.tsGrantor interaction feed and mutations
useGrantPipelineListfeatures/grants/hooks/useGrants.tsQuery-backed pipeline list
useGrantsfeatures/grants/GrantContext.tsxLegacy grants compatibility hook backed by canonical query hooks
useGrantsListfeatures/grants/hooks/useGrants.tsAggregate query-backed grants collections
useOrgPortalfeatures/grantors/hooks/useOrgPortal.tsGrantor portal data/actions
usePipelineEntryfeatures/grants/GrantContext.tsxSelect a single pipeline entry from grants data
useReportingDeadlinesfeatures/grantors/hooks/useReportingDeadlines.tsReporting calendar and deadline utilities
useApprovedJournalsfeatures/journals/JournalGenerationContext.tsxFilter approved journals
useJournalfeatures/journals/hooks/useJournals.tsQuery-backed single journal entry
useJournalsfeatures/journals/hooks/useJournals.tsQuery-backed journals list and mutations
useJournalsByDateRangefeatures/journals/JournalGenerationContext.tsxFilter journals by date range
useJournalsByMonthfeatures/journals/JournalGenerationContext.tsxFilter journals by month
useJournalsByProjectfeatures/journals/JournalGenerationContext.tsxFilter journals by project
useJournalsByProjectIdsfeatures/journals/JournalGenerationContext.tsxFilter journals by project ids
useJournalsByStatusfeatures/journals/JournalGenerationContext.tsxFilter journals by status
useJournalsByUserfeatures/journals/JournalGenerationContext.tsxFilter journals by user
useJournalsThisMonthfeatures/journals/JournalGenerationContext.tsxCurrent month journals
useJournalsThisWeekfeatures/journals/JournalGenerationContext.tsxCurrent week journals
useJournalsTodayfeatures/journals/JournalGenerationContext.tsxToday’s journals
useLockedJournalsfeatures/journals/JournalGenerationContext.tsxLocked journals subset
usePendingJournalsfeatures/journals/JournalGenerationContext.tsxPending journals subset
useActivityHistoryStatefeatures/mission/hooks/useActivityHistoryState.tsMission activity history state
useNotificationHistoryStatefeatures/notifications/hooks/useNotificationHistoryState.tsNotification history list/filter state
useNotificationsTRPCfeatures/notifications/hooks/useNotificationsTRPC.tsNotifications tRPC mutations
usePartnershipsDashboardStatefeatures/partnerships/hooks/usePartnershipsDashboardState.tsPartnerships dashboard state
usePortalAnalyticsStatefeatures/impact-portal/hooks/usePortalAnalyticsState.tsImpact portal analytics state
useActiveProjectsfeatures/projects/ProjectContext.tsxActive projects selector
useArchivedProjectsfeatures/projects/ProjectContext.tsxArchived projects selector
useNonArchivedProjectsfeatures/projects/ProjectContext.tsxNon-archived projects selector
useOutstandingTasksCountfeatures/projects/hooks/useOutstandingTasksCount.tsOutstanding tasks count for the current user
useProjectfeatures/projects/ProjectContext.tsxSingle project lookup
useProjectsfeatures/projects/ProjectContext.tsxProjects compatibility hook backed by canonical query hooks
useProjectsByIdsfeatures/projects/ProjectContext.tsxProjects filtered by ids
useProjectsByPhasefeatures/projects/ProjectContext.tsxProjects filtered by phase
useProjectsByStatusfeatures/projects/ProjectContext.tsxProjects filtered by status
useContactAnalyticsfeatures/relations/hooks/useContactAnalytics.tsContact analytics hook
useInteractionsFeedfeatures/relations/hooks/useInteractionsFeed.tsInteractions feed hook
useSegmentsfeatures/relations/hooks/useSegments.tsSegments list and mutation hook
useActiveUsersfeatures/users/UserContext.tsxActive users selector
useCurrentUserfeatures/users/UserContext.tsxCurrent user profile selector
useInvitedUsersfeatures/users/UserContext.tsxInvited users selector
useUserfeatures/users/UserContext.tsxSingle user lookup
useUserByEmailfeatures/users/UserContext.tsxUser lookup by email
useUsersfeatures/users/UserContext.tsxUsers compatibility hook
useUsersByIdsfeatures/users/UserContext.tsxUsers filtered by ids
useUsersByManagerfeatures/users/UserContext.tsxUsers filtered by manager
useUsersByRolefeatures/users/UserContext.tsxUsers filtered by role
useUsersByStatusfeatures/users/UserContext.tsxUsers filtered by status
useUsersBySystemRolefeatures/users/UserContext.tsxUsers filtered by system role
Context hooks (from src/contexts/):
HookSourcePurpose
useTenantTenantContext.tsxCurrent organization context (org data + actions)
useTenantDataTenantContext.tsxOrganization data only (fewer re-renders)
useTenantActionsTenantContext.tsxStable action callbacks only
useAuthAuthContext.tsxAuthentication state
useRolesRoleContext.tsxRole definitions and management
useRoleRoleContext.tsxSingle role lookup by ID
useRoleByNameRoleContext.tsxRole lookup by name
useModulesExtensionContext.tsxExtension/module system

useZodForm

Source: src/hooks/useZodForm.ts
Standardized form handling combining react-hook-form with Zod schema validation. All new forms must use this hook — useValidatedForm is deprecated.
const {
  form, handleSubmit, isSubmitting, isDirty, isValid,
  reset, getFieldError, hasFieldError,
  register, control, errors, setValue, watch, trigger,
} = useZodForm({
  schema: myZodSchema,
  defaultValues: { amount: 0, description: '' },
  onSubmit: async (data) => { await save(data); },
  successMessage: 'Saved successfully',
});

Options (UseZodFormOptions<TSchema>)

PropTypeDefaultDescription
schemaz.ZodTyperequiredZod schema for validation
defaultValuesDefaultValues<z.infer<TSchema>>Initial form values
onSubmit(data) => Promise<void> | voidrequiredSuccess callback
onError(error: unknown) => voidCustom error handler
successMessagestringToast shown on success
errorMessagePrefixstring'Form submission failed'Error toast prefix
resetOnSuccessbooleanfalseReset form after success
mode'onBlur' | 'onChange' | 'onSubmit' | 'onTouched' | 'all''onBlur'Validation trigger mode

Return Value (UseZodFormReturn<TSchema>)

FieldTypeDescription
formUseFormReturnUnderlying react-hook-form instance
handleSubmit(e?) => Promise<void>Submit handler for <form onSubmit>
isSubmittingbooleanCurrently submitting
isDirtybooleanForm has been modified
isValidbooleanForm passes validation
reset() => voidReset to default values
getFieldError(name) => string | undefinedError message for a field
hasFieldError(name) => booleanWhether field has error
registerUseFormReturn['register']Field registration
controlUseFormReturn['control']Control object for Controller
errorsFormState['errors']All validation errors
setValueUseFormReturn['setValue']Programmatic value setter
watchUseFormReturn['watch']Watch field values
triggerUseFormReturn['trigger']Trigger validation manually

Behavior

  • Validation: Runs Zod schema validation via zodResolver. Default mode is onBlur.
  • Error handling: Errors are logged via handleError() (Sentry + console) and shown as toast notifications.
  • Success toast: If successMessage is provided, a success toast is shown automatically.
  • Reset: When resetOnSuccess is true, form resets to defaultValues after successful submission.

useGrantsList

Source: src/features/grants/hooks/useGrants.ts
Canonical grants read hook. It aggregates opportunities, pipeline entries, applications, and active grants behind one query-backed surface.
const {
  data: { opportunities, pipeline, applications, activeGrants },
  isLoading,
  error,
  refetch,
  status,
} = useGrantsList();

Return Value

FieldTypeDescription
data.opportunitiesGrantOpportunity[]Discovery opportunities
data.pipelineGrantPipelineEntry[]Pipeline entries
data.applicationsGrantApplication[]Grant applications
data.activeGrantsActiveGrant[]Post-award active grants
isLoadingbooleanCombined loading state across all grant collections
errorError | nullFirst query error, if any
refetch() => Promise<void>Refetch all grant collections
statusobjectPer-collection loading flags

Behavior

  • Uses feature services rather than Firebase imports in the hook.
  • Acts as the default owner for grants feature collections.
  • Replaces provider-owned canonical grant collection state.

useGrant

Source: src/features/grants/hooks/useGrants.ts
Query-backed lookup for a single active grant by id.
const { data: grant, isLoading, error } = useGrant(grantId);
When grantId is missing, data resolves to null.

useGrantMutations

Source: src/features/grants/hooks/useGrants.ts
Canonical grants write surface. All mutations delegate to GrantService and invalidate the grants query keys on success.
const {
  addToPipeline,
  saveApplication,
  submitApplication,
  updateActiveGrant,
} = useGrantMutations();

Included Mutations

  • addToPipeline(opportunity, initialData?)
  • createOpportunity(opportunity)
  • updatePipelineStage(entryId, newStage, reason?)
  • updatePipelineEntry(entry)
  • removePipelineEntry(entryId)
  • saveApplication(application, isNew?)
  • submitApplication(applicationId, confirmationNumber?)
  • convertToActiveGrant(pipelineEntry, opportunity, applicationId, grantDetails)
  • updateActiveGrant(grant)

useProjects

Source: src/hooks/useProjects.ts
CRUD operations for projects within a tenant organization. All mutations are optimistically applied, audit-logged, and trigger admin notifications.
const {
  projects,
  loading,
  error,
  addProject,
  updateProject,
  deleteProject,
} = useProjects({ organizationId });

Options

PropTypeDescription
organizationIdstring?Tenant organization ID. When absent, returns empty project list.

Return Value

FieldTypeDescription
projectsProject[]Current project list
loadingbooleantrue during initial fetch
errorError | nullFetch error, if any
addProject(project: Project) => Promise<void>Create a project (checks quota first)
updateProject(project: Project) => Promise<void>Update a project (notifies admins of changes)
deleteProject(id: string) => Promise<void>Delete a project

Behavior

  • Quota enforcement: addProject calls checkQuotaCompliance() and blocks creation if the project limit is reached.
  • Optimistic updates: State is updated immediately; rolled back on error.
  • Audit logging: All CRUD operations log PROJECT_CREATED, PROJECT_UPDATED, or PROJECT_DELETED events.
  • Notifications: addProject and updateProject notify organization admins.

useIntegrations

Source: src/hooks/useIntegrations.ts
Manages the organization’s integration surface: export records, API keys, webhooks, and audit logs. Scoped to the current tenant via useTenant().
const {
  loading,
  exports, apiKeys, webhooks, auditLogs,
  addExport, removeExport,
  addApiKey, revokeApiKey,
  addWebhook, editWebhook, toggleWebhook, removeWebhook,
  getWebhookLogs,
  refresh,
} = useIntegrations();

Return Value

FieldTypeDescription
loadingbooleantrue during initial parallel fetch
exportsIntegrationRecord[]Data export records
apiKeysApiKey[]Organization API keys
webhooksWebhookConfig[]Webhook endpoint configurations
auditLogsAuditLogEntry[]Integration audit log entries
addExport(record) => Promise<void>Create an export record
removeExport(id) => Promise<void>Delete an export record
addApiKey(key) => Promise<void>Create an API key
revokeApiKey(id) => Promise<void>Revoke (soft-delete) an API key
addWebhook(webhook) => Promise<void>Create a webhook endpoint
editWebhook(webhook) => Promise<void>Update a webhook configuration
toggleWebhook(id) => Promise<void>Toggle a webhook’s active/inactive state
removeWebhook(id) => Promise<void>Delete a webhook
getWebhookLogs(webhookId) => Promise<WebhookLog[]>Fetch delivery logs for a webhook
refresh() => Promise<void>Reload all integration data

useGrantors

Source: src/hooks/useGrantors.ts
CRUD for the global grantor (funder) taxonomy. Grantors are shared across all projects and used in grant applications, pipeline tracking, and compliance reporting.
const {
  grantors,
  loading,
  error,
  addGrantor,
  editGrantor,
  removeGrantor,
} = useGrantors();

Return Value

FieldTypeDescription
grantorsTaxonomyItem[]Grantor taxonomy items
loadingbooleantrue during initial fetch
errorstring | nullError message, if any
addGrantor(grantor: TaxonomyItem) => Promise<boolean>Create a grantor (returns true on success)
editGrantor(grantor: TaxonomyItem) => Promise<boolean>Update a grantor
removeGrantor(id: string) => Promise<boolean>Delete a grantor

Behavior

  • Requires authenticated user — waits for useAuth() to resolve before fetching.
  • Stamps new grantors with createdBy (UID) and createdAt for Firestore security rules.

useKeyboardShortcuts

Source: src/hooks/useKeyboardShortcuts.ts
Registers global keyboard shortcuts on window. Automatically skips shortcuts when focus is inside <input>, <textarea>, or contentEditable elements (Cmd/Ctrl+K is always allowed).
useKeyboardShortcuts(shortcuts: ShortcutConfig[], options?: { enabled?: boolean });

useKeyboardShortcut

Convenience wrapper for a single shortcut:
useKeyboardShortcut(config: ShortcutConfig, options?: { enabled?: boolean });

Utility Functions

FunctionSignatureDescription
isMac()() => booleanDetect macOS platform
getModifierLabel(modifier)('cmd' | 'ctrl' | 'alt' | 'shift') => stringPlatform-appropriate modifier symbol ( vs Ctrl)
formatShortcut(shortcut)(Partial<ShortcutConfig>) => stringFormat shortcut for display (⌘K or Ctrl+K)

Intelligence Hooks

Source: src/hooks/useIntelligence.ts
Composable hooks for the cross-organization Intelligence module. Available individually or combined.

useIntelligence (combined)

Aggregates all intelligence sub-hooks into a single return object. Also computes featureAccess based on the organization’s subscription tier.
const {
  // Consent
  consent, isOptedIn, isLoadingConsent, consentError,
  grantConsent, withdrawConsent, requestDeletion,
  // Benchmarks
  benchmarks, isLoadingBenchmarks, benchmarksError, refreshBenchmarks, cohortDescription,
  // Funder Intelligence
  funderProfiles, funderInsights, isLoadingFunderData, funderError,
  // Trends
  trends, isLoadingTrends,
  // Feature Access
  featureAccess,
  // Refresh
  refreshAll,
} = useIntelligence();

useConsent

Manage the current organization’s intelligence data-sharing consent.
const {
  consent, isOptedIn, isLoading, error,
  grantConsent, withdrawConsent, requestDeletion, refresh,
} = useConsent();
MethodSignatureDescription
grantConsent(categories?: IntelligenceDataCategory[]) => Promise<boolean>Opt in to data sharing
withdrawConsent(reason?: string) => Promise<boolean>Opt out of data sharing
requestDeletion() => Promise<boolean>Request full data deletion

useBenchmarks

Fetch anonymized sector benchmarks for the current organization.
const { benchmarks, cohortDescription, isLoading, error, refresh } = useBenchmarks();
FieldTypeDescription
benchmarksOrgBenchmarkPosition[]Benchmark positions (grant success rate, budget utilization, etc.)
cohortDescriptionstringHuman-readable cohort description

useFunderIntelligence

Access funder profiles and organization-specific funder insights.
const { profiles, insights, isLoading, error, refresh } = useFunderIntelligence();
FieldTypeDescription
profilesFunderProfile[]Aggregated public funder data
insightsFunderInsight[]Tailored recommendations for the current org

useSectorTrends

Fetch aggregated sector-level funding trends.
const { trends, isLoading, error, refresh } = useSectorTrends(sectors?: string[]);
ParamTypeDescription
sectorsstring[]?Optional sector filter (e.g. ['healthcare', 'education'])

Common Patterns

Optimistic Updates

Most mutation hooks follow this pattern:
  1. Update local state immediately
  2. Call the service layer
  3. On error: rollback local state + show toast

Audit Logging

Hooks that modify data (useProjects) automatically log audit events with logAuditEvent(). Both success and failure outcomes are logged.

Tenant Scoping

All hooks scope data to the current organization via either:
  • useTenant()organization.id (automatic)
  • organizationId option parameter (explicit)