React Hooks API

HumanBehavior SDK provides React hooks and context providers for seamless integration with React applications.
How to find your Public API Key:
Flow: Project Home → Settings (on sidebar) → Public API Key
Where to find your Public API Key

Example screenshot – your actual API key will be different.

HumanBehaviorProvider

The main provider component that wraps your React application.

Props

interface HumanBehaviorProviderProps {
  apiKey?: string;
  client?: HumanBehaviorTracker;
  children: ReactNode;
}
Parameters:
  • apiKey (string, optional): Your HumanBehavior API key
  • client (HumanBehaviorTracker, optional): Existing tracker instance
  • children (ReactNode, required): React components to wrap
Example:
import { HumanBehaviorProvider } from 'humanbehavior-js/react';

function App() {
  return (
    <HumanBehaviorProvider apiKey="your-api-key-here">
      <YourApp />
    </HumanBehaviorProvider>
  );
}

Usage Patterns

With API Key

<HumanBehaviorProvider apiKey="your-api-key-here">
  <YourApp />
</HumanBehaviorProvider>

With Existing Client

import { HumanBehaviorTracker } from 'humanbehavior-js';

const tracker = HumanBehaviorTracker.init('your-api-key');

<HumanBehaviorProvider client={tracker}>
  <YourApp />
</HumanBehaviorProvider>

useHumanBehavior

Hook that provides access to the HumanBehavior tracker instance.

Returns

Returns an object with the following methods:
interface HumanBehaviorInterface {
  addEvent: (event: any) => void;
  addUserInfo: (userProperties: Record<string, any>) => Promise<void>;
  start: () => Promise<void>;
  stop: () => Promise<void>;
  setRedactedFields: (fields: string[]) => void;
  isRedactionActive: () => boolean;
  getRedactedFields: () => string[];
  redact: (options?: RedactionOptions) => Promise<void>;
  auth: (authFields: string[]) => Promise<void>;
  getUserInfo: () => {
    endUserId: string | null;
    sessionId: string;
    isPreexistingUser: boolean;
    initialized: boolean;
  };
  getSessionId: () => string;
  getCurrentUrl: () => string;
}

Example

import { useHumanBehavior } from 'humanbehavior-js/react';

function MyComponent() {
  const tracker = useHumanBehavior();
  
  useEffect(() => {
    tracker.start();
  }, [tracker]);
  
  const handleClick = () => {
    tracker.customEvent('button_click', { buttonId: 'my-button' });
  };
  
  return <button onClick={handleClick}>Click me</button>;
}

Available Methods

addEvent(event)

Adds a raw event to the session recording. Parameters:
  • event (object, required): Raw event object
Returns: void Example:
const tracker = useHumanBehavior();

tracker.addEvent({
  type: 'custom',
  data: { action: 'test' },
  timestamp: Date.now()
});

addUserInfo(userProperties)

Adds or updates user information for the current session. Parameters:
  • userProperties (object, required): User properties to track
Returns: Promise<void> Example:
const tracker = useHumanBehavior();

await tracker.addUserInfo({
  email: 'user@example.com',
  name: 'John Doe',
  userId: '12345'
});

start()

Starts session recording. Returns: Promise<void> Example:
const tracker = useHumanBehavior();

useEffect(() => {
  tracker.start();
}, [tracker]);

stop()

Stops session recording. Returns: Promise<void> Example:
const tracker = useHumanBehavior();

const handleStop = () => {
  tracker.stop();
};

setRedactedFields(fields)

Sets the fields that should be redacted during recording. Parameters:
  • fields (string[], required): Array of CSS selectors for fields to redact
Returns: void Example:
const tracker = useHumanBehavior();

useEffect(() => {
  tracker.setRedactedFields([
    'input[type="password"]',
    'input[type="email"]'
  ]);
}, [tracker]);

isRedactionActive()

Checks if redaction is currently active. Returns: boolean Example:
const tracker = useHumanBehavior();

const isActive = tracker.isRedactionActive();
console.log('Redaction active:', isActive);

getRedactedFields()

Gets the currently selected fields for redaction. Returns: string[] Example:
const tracker = useHumanBehavior();

const fields = tracker.getRedactedFields();
console.log('Redacted fields:', fields);

redact(options)

Enable data redaction for sensitive fields. Parameters:
  • options (RedactionOptions, optional): Redaction configuration
Returns: Promise<void> Example:
const tracker = useHumanBehavior();

await tracker.redact({
  maskTextInputs: true,
  maskAllText: false
});

auth(authFields)

Authenticates the current user against your database. Parameters:
  • authFields (string[], required): Array of field names to use for authentication
Returns: Promise<void> Example:
const tracker = useHumanBehavior();

// First add user info
await tracker.addUserInfo({
  email: 'user@example.com',
  phone: '+1234567890'
});

// Then authenticate
await tracker.auth(['email', 'phone']);

getUserInfo()

Get comprehensive user information. Returns: User information object Example:
const tracker = useHumanBehavior();

const userInfo = tracker.getUserInfo();
console.log('User ID:', userInfo.endUserId);
console.log('Session ID:', userInfo.sessionId);
console.log('Is existing user:', userInfo.isPreexistingUser);

getSessionId()

Get the current session ID. Returns: string Example:
const tracker = useHumanBehavior();

const sessionId = tracker.getSessionId();
console.log('Current session:', sessionId);

getCurrentUrl()

Get the current URL being tracked. Returns: string Example:
const tracker = useHumanBehavior();

const currentUrl = tracker.getCurrentUrl();
console.log('Current URL:', currentUrl);

Context Usage

Direct Context Access

You can access the context directly if needed:
import { useContext } from 'react';
import { HumanBehaviorContext } from 'humanbehavior-js/react';

function MyComponent() {
  const { humanBehavior, queueEvent } = useContext(HumanBehaviorContext);
  
  if (humanBehavior) {
    // Tracker is initialized
    humanBehavior.start();
  } else {
    // Tracker is not initialized yet, queue the event
    queueEvent({ type: 'custom', data: { action: 'test' } });
  }
  
  return <div>My Component</div>;
}

Error Handling

Provider Errors

function App() {
  return (
    <HumanBehaviorProvider apiKey="invalid-key">
      <ErrorBoundary>
        <YourApp />
      </ErrorBoundary>
    </HumanBehaviorProvider>
  );
}

Hook Errors

function MyComponent() {
  const tracker = useHumanBehavior();
  
  const handleAction = async () => {
    try {
      await tracker.customEvent('action', { data: 'value' });
    } catch (error) {
      console.error('Failed to track event:', error);
    }
  };
  
  return <button onClick={handleAction}>Action</button>;
}

SSR Compatibility

Server-Side Rendering

The provider automatically handles SSR:
// Works in both client and server environments
function App() {
  return (
    <HumanBehaviorProvider apiKey="your-api-key">
      <YourApp />
    </HumanBehaviorProvider>
  );
}

Hydration

The SDK handles hydration gracefully:
function MyComponent() {
  const tracker = useHumanBehavior();
  
  useEffect(() => {
    // This runs only on the client after hydration
    tracker.start();
  }, [tracker]);
  
  return <div>Content</div>;
}

Performance Optimization

Memoization

import { useCallback, useMemo } from 'react';

function OptimizedComponent() {
  const tracker = useHumanBehavior();
  
  const handleClick = useCallback(() => {
    tracker.customEvent('button_click', { component: 'OptimizedComponent' });
  }, [tracker]);
  
  const userInfo = useMemo(() => ({
    email: 'user@example.com',
    name: 'John Doe'
  }), []);
  
  useEffect(() => {
    tracker.addUserInfo(userInfo);
  }, [tracker, userInfo]);
  
  return <button onClick={handleClick}>Click me</button>;
}

Conditional Tracking

function ConditionalTracker({ shouldTrack }) {
  const tracker = useHumanBehavior();
  
  useEffect(() => {
    if (shouldTrack) {
      tracker.start();
    } else {
      tracker.stop();
    }
  }, [shouldTrack, tracker]);
  
  return null;
}

Testing

Mock Provider

// test-utils.js
import { HumanBehaviorProvider } from 'humanbehavior-js/react';

const mockTracker = {
  addEvent: jest.fn(),
  addUserInfo: jest.fn(),
  customEvent: jest.fn(),
  start: jest.fn(),
  stop: jest.fn(),
  viewLogs: jest.fn(),
  setRedactedFields: jest.fn(),
  isRedactionActive: jest.fn(),
  getRedactedFields: jest.fn(),
  auth: jest.fn()
};

export function TestProvider({ children }) {
  return (
    <HumanBehaviorProvider client={mockTracker}>
      {children}
    </HumanBehaviorProvider>
  );
}

Component Testing

import { render, screen } from '@testing-library/react';
import { TestProvider } from './test-utils';
import MyComponent from './MyComponent';

test('tracks button click', async () => {
  render(
    <TestProvider>
      <MyComponent />
    </TestProvider>
  );
  
  const button = screen.getByText('Click me');
  await button.click();
  
  expect(mockTracker.customEvent).toHaveBeenCalledWith(
    'button_click',
    expect.any(Object)
  );
});
Version 0.1.6: Enhanced React integration with improved SSR support, better error handling, full access to all tracker methods through the hook interface, and comprehensive health endpoint monitoring.