React state management hooks for TrustGraph applications. Provides TanStack Query hooks and Zustand stores for managing application state with a pluggable notification system.
- 🔌 Pluggable Notifications - Component-free notification system with provider pattern
- 📊 TanStack Query Hooks - Data fetching and caching for all TrustGraph operations
- 🗃️ Zustand Stores - Lightweight state management for UI state
- 🎯 TypeScript Support - Full type definitions included
- 🚫 Zero UI Dependencies - Bring your own notification/toast UI
- 🔗 WebSocket Integration - Works seamlessly with @trustgraph/react-provider
npm install @trustgraph/react-state @trustgraph/react-provider @trustgraph/client
import { SocketProvider } from "@trustgraph/react-provider";
import { NotificationProvider, NotificationHandler } from "@trustgraph/react-state";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Create your notification handler (example with toast library)
const notificationHandler: NotificationHandler = {
success: (message) => toast.success(message),
error: (message) => toast.error(message),
warning: (message) => toast.warning(message),
info: (message) => toast.info(message),
};
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<NotificationProvider handler={notificationHandler}>
<SocketProvider user="your-user" apiKey="optional-api-key">
<YourApp />
</SocketProvider>
</NotificationProvider>
</QueryClientProvider>
);
}
import { useLibrary, useFlows, useSettings } from "@trustgraph/react-state";
function MyComponent() {
const { documents, deleteDocuments, isLoading } = useLibrary();
const { flows, startFlow } = useFlows();
const { settings, updateSetting } = useSettings();
return (
<div>
{isLoading ? "Loading..." : `${documents?.length} documents`}
</div>
);
}
The package uses a pluggable notification system that allows you to integrate any toast/notification UI library.
interface NotificationHandler {
success: (message: string) => void;
error: (message: string) => void;
warning: (message: string) => void;
info: (message: string) => void;
}
With Chakra UI:
import { toaster } from "@chakra-ui/react";
const handler: NotificationHandler = {
success: (msg) => toaster.create({ title: msg, type: "success" }),
error: (msg) => toaster.create({ title: `Error: ${msg}`, type: "error" }),
warning: (msg) =>
toaster.create({ title: `Warning: ${msg}`, type: "warning" }),
info: (msg) => toaster.create({ title: msg, type: "info" }),
};
With react-hot-toast:
import toast from "react-hot-toast";
const handler: NotificationHandler = {
success: (msg) => toast.success(msg),
error: (msg) => toast.error(msg),
warning: (msg) => toast(msg, { icon: "⚠️" }),
info: (msg) => toast(msg),
};
With console (testing):
const handler: NotificationHandler = {
success: (msg) => console.log("✓", msg),
error: (msg) => console.error("✗", msg),
warning: (msg) => console.warn("⚠", msg),
info: (msg) => console.info("ℹ", msg),
};
useLibrary()
- Manage documents, upload files, submit for processinguseProcessing()
- Track document processing status
useTriples()
- Query RDF triplesuseGraphSubgraph()
- Retrieve graph subgraphsuseGraphEmbeddings()
- Query graph embeddingsuseVectorSearch()
- Perform vector similarity searchuseEntityDetail()
- Get entity detailsuseNodeDetails()
- Get node information
useFlows()
- Manage processing flowsuseFlowClasses()
- Get available flow classesuseFlowParameters()
- Get flow parameter schemas
useCollections()
- Manage document collectionsuseKnowledgeCores()
- Manage knowledge cores
useChat()
- Chat interface operationsuseChatQuery()
- Chat query managementuseStructuredQuery()
- Structured query operationsuseObjectsQuery()
- Object queriesuseNlpQuery()
- Natural language processing queries
useSettings()
- Application settings managementusePrompts()
- Manage promptsuseSchemas()
- Manage schemasuseOntologies()
- Manage ontologiesuseLLMModels()
- LLM model configurationuseTokenCosts()
- Token cost tracking
useAgentTools()
- Agent tool managementuseMcpTools()
- MCP tool management
useEmbeddings()
- Generate text embeddings
useProgressStateStore()
- Activity indicators and error stateuseSessionStore()
- Session and flow stateuseChatStateStore()
- Chat message historyuseWorkbenchStateStore()
- Workbench UI state (selected entity, tool, etc.)useLoadStateStore()
- Document loading state
useNotification()
- Access notification handleruseActivity()
- Show/hide activity indicators
import { useLibrary } from "@trustgraph/react-state";
function DocumentManager() {
const {
documents,
isLoading,
deleteDocuments,
uploadFiles,
submitDocuments,
} = useLibrary();
const handleDelete = (ids: string[]) => {
deleteDocuments({
ids,
onSuccess: () => console.log("Deleted successfully"),
});
};
const handleUpload = (files: File[]) => {
uploadFiles({
files,
params: { title: "My Document", keywords: [] },
mimeType: "application/pdf",
user: "current-user",
});
};
if (isLoading) return <div>Loading...</div>;
return (
<div>
{documents?.map((doc) => (
<div key={doc.id}>{doc.title}</div>
))}
</div>
);
}
import { useSettings } from "@trustgraph/react-state";
function SettingsPanel() {
const { settings, updateSetting, saveSettings, exportSettings } = useSettings();
return (
<div>
<input
value={settings.user}
onChange={(e) => updateSetting("user", e.target.value)}
/>
<input
value={settings.collection}
onChange={(e) => updateSetting("collection", e.target.value)}
/>
<button onClick={() => console.log(exportSettings())}>
Export Settings
</button>
</div>
);
}
import { useProgressStateStore, useActivity } from "@trustgraph/react-state";
function MyComponent() {
const [isLoading, setIsLoading] = useState(false);
// Automatically shows "Processing data" in activity indicators while isLoading is true
useActivity(isLoading, "Processing data");
// Access all current activities
const activities = useProgressStateStore((state) => state.activity);
return (
<div>
{activities.size > 0 && (
<div>Active: {Array.from(activities).join(", ")}</div>
)}
</div>
);
}
The package re-exports types from @trustgraph/client
for convenience:
import type {
Triple,
Value,
Entity,
Message,
Settings,
NotificationHandler,
// ... and more
} from "@trustgraph/react-state";
The package also exports utility functions:
import {
fileToBase64,
textToBase64,
vectorSearch,
getTriples,
prepareMetadata,
createDocId,
} from "@trustgraph/react-state";
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm test
# Run linting
npm run lint
# Type checking
npm run typecheck
react
^18.0.0@tanstack/react-query
^5.0.0@trustgraph/client
^0.1.0@trustgraph/react-provider
^0.1.0zustand
^4.0.0 || ^5.0.0
compute-cosine-similarity
- Vector similarity calculationsuuid
- Unique ID generation
Apache 2.0
(c) KnowNext Inc., KnowNext Limited 2025