useAgent Hook
Access the underlying Heylock SDK instance created by the nearest provider.
Basic Usage
1import { useAgent } from '@heylock-dev/ui';
2
3export function Ask() {
4 const agent = useAgent();
5
6 async function handleAsk(){
7 try {
8 const response = await agent.message('How was your day?');
9
10 console.log(response);
11 } catch (error) {
12 console.error('Failed to send message:', error);
13 }
14 }
15
16 return (
17 <button onClick={handleAsk} >Ask a question</button>
18 );
19}
Context Updates
Add context entries reacting to UI events.
1import { useEffect } from 'react';
2
3export function Track({ pageName }) {
4 const agent = useAgent();
5
6 useEffect(() => {
7 agent.addContextEntry(`User opened ${pageName}`);
8 }, [agent]);
9
10 return null;
11}
Cleanup
Always unsubscribe in effects to prevent retained handlers.
1import { useAgent } from '@heylock-dev/ui';
2import { useEffect } from 'react';
3
4export function Subscriptions() {
5 const agent = useAgent();
6
7 useEffect(() => {
8 // Subscribe to message history changes
9 const unsubscribe = agent.onMessageHistoryChange(history => {
10 console.log('Messages', history.length);
11 });
12
13 // Cleanup subscription on unmount or agent change
14 return () => {
15 if (typeof unsubscribe === 'function') {
16 unsubscribe();
17 }
18 };
19 }, [agent]);
20
21 return null;
22}
Learn More
See SDK introduction.