useAIContext
The useAIContext
hook allows React components to share their state with the AI without causing re-renders. This enables the AI to provide personalized responses based on user data, app settings, and component state.
Syntax
function useAIContext(
options: {
description: string;
value: unknown;
priority?: number;
categories?: string[];
parentId?: string;
available?: "enabled" | "disabled";
dump?: (description: string, value: unknown) => string;
},
dependencies?: unknown[]
): string | undefined
Parameters
Field | Type | Required | Description |
---|---|---|---|
options.description | string | Yes | Human-readable description of this context item |
options.value | unknown | Yes | Data to dump and include in the context line |
options.priority | number | No | Higher numbers are sent first |
options.categories | string[] | No | Optional categories to group context |
options.parentId | string | No | Optional parent context id for grouping |
options.available | `“enabled" | "disabled”` | No |
options.dump | (description, value) => string | No | Custom dump function to produce the context text |
dependencies | unknown[] | No | Extra deps to recompute when using custom dump |
Examples
Priority System
Higher priority context items are sent first to the AI. Use priorities to ensure critical context is always included:
// High priority - critical user info
useAIContext({ description: "User Auth", value: authData, priority: 100 });
// Medium priority - app state
useAIContext({ description: "App Settings", value: settings, priority: 80 });
// Low priority - metadata
useAIContext({ description: "Session Info", value: sessionData, priority: 60 });
Examples
Basic Usage
import { useAIContext } from "ai-chat-bootstrap";
function UserProfile() {
const [user, setUser] = useState({
name: "Alice Johnson",
role: "admin",
plan: "pro"
});
// Share user profile with AI
useAIContext({ description: "User Profile", value: user, priority: 100 });
return <div>...</div>;
}
Dynamic Context Updates
Context automatically updates when your state changes:
function TaskManager() {
const [currentTask, setCurrentTask] = useState(null);
// Context updates automatically when task changes
useAIContext({
description: "Active Task",
value: currentTask ? {
id: currentTask.id,
title: currentTask.title,
status: currentTask.status,
dueDate: currentTask.dueDate,
} : { message: "No active task" },
priority: 90,
});
return <div>...</div>;
}
Multiple Context Items
A single component can register multiple context items:
function Dashboard() {
const [user, setUser] = useState(userData);
const [projects, setProjects] = useState(projectsData);
const [notifications, setNotifications] = useState(notificationsData);
// User context
useAIContext({ description: "User", value: user, priority: 100 });
// Projects context
useAIContext({
description: "Projects",
value: {
activeProjects: projects.filter(p => p.status === 'active'),
totalCount: projects.length,
},
priority: 80,
});
// Notifications context
useAIContext({
description: "Notifications",
value: {
unreadCount: notifications.filter(n => !n.read).length,
latestNotification: notifications[0],
},
priority: 60,
});
return <div>...</div>;
}
Conditional Context
Only share context when certain conditions are met:
function ConditionalContext() {
const [user, setUser] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
// Only share user context when authenticated
useAIContext({
description: "User Authentication",
value: isAuthenticated && user ? {
id: user.id,
name: user.name,
permissions: user.permissions,
} : { authenticated: false },
priority: 100,
});
return <div>...</div>;
}
Backend Integration
The backend automatically receives context items in the request payload (enrichedSystemPrompt
embeds context/focus/tool summaries):
import { createAzure } from "@ai-sdk/azure";
import { convertToModelMessages, streamText } from "ai";
const azure = createAzure({
resourceName: process.env.AZURE_RESOURCE_NAME!,
apiKey: process.env.AZURE_API_KEY!,
apiVersion: process.env.AZURE_API_VERSION ?? "preview",
});
const model = azure(process.env.AZURE_DEPLOYMENT_ID!);
export async function POST(req: Request) {
const { messages, enrichedSystemPrompt, tools, context, focus } = await req.json();
const result = await streamText({
model,
messages: [
{ role: "system", content: enrichedSystemPrompt },
...convertToModelMessages(messages),
],
tools,
experimental_providerMetadata: { context, focus },
});
return result.toUIMessageStreamResponse();
}
Note: Do not re-concatenate context data into the system prompt on the server. The client-generated
enrichedSystemPrompt
already contains a standardized preamble and conditional sections (Tools / Context / Focus) plus the originalsystemPrompt
(if supplied). Rebuilding would cause duplication and potential truncation.
TypeScript Interface
interface ContextItem {
id: string;
text: string;
description?: string;
priority?: number;
categories?: string[];
parentId?: string;
}
Performance Considerations
Preventing Re-render Loops
The useAIContext
hook follows the critical Zustand pattern to prevent infinite re-renders:
// ✅ Correct - Only include stable values in dependencies
useEffect(() => {
setContextItem(contextData);
return () => removeContextItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, data, opts?.label, opts?.description, opts?.scope, opts?.priority]);
// ❌ Wrong - Including Zustand actions causes infinite loops
}, [id, data, setContextItem, removeContextItem]); // Don't do this!
Memory Management
- Context items are automatically cleaned up when components unmount
- Session-scoped items persist across conversations until unmount
- Conversation-scoped items are cleared when conversations change
- Message-scoped items are cleared after each message
Best Practices
- Keep data serializable: Avoid functions, DOM nodes, or complex objects
- Use meaningful IDs: Choose descriptive, unique identifiers
- Prioritize wisely: Ensure critical context has higher priority
- Avoid sensitive data: Never share passwords, API keys, or PII
- Use
useMemo
for expensive computations: Optimize performance for complex context
See Also
- Sharing Context guide - Complete tutorial with live examples
- useAIFocus - For user-controlled focus items
- useAIChat - Main chat hook