Using HumanBehaviorTracker with React

Quickstart

Human Behavior works seamlessly to record sessions on your React app. React is a JavaScript library for building user interfaces, and HumanBehavior provides a complete React integration with hooks, context providers, and automatic session management.

Step 1: Installation

npm install humanbehavior-js
# or
yarn add humanbehavior-js

Step 2: Basic Setup

Use the Built-in React Provider

The HumanBehaviorTracker comes with a built-in React provider that handles all the complexity for you! No need to create your own.

Provider Options

The HumanBehaviorProvider accepts these options:
<HumanBehaviorProvider 
  apiKey="your-api-key-here"
  options={{
    ingestionUrl: 'https://custom-endpoint.com', // Optional: Custom ingestion endpoint
    logLevel: 'debug', // Optional: 'none' | 'error' | 'warn' | 'info' | 'debug'
    redactFields: ['input[type="password"]', '.sensitive'] // Optional: Fields to redact
  }}
>
  {children}
</HumanBehaviorProvider>

Add the Provider to Your App

In your main App component or entry point:
import React from 'react'
import { HumanBehaviorProvider } from 'humanbehavior-js/react'

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

export default App

With React Router

If you’re using React Router, wrap your router with the provider:
import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import { HumanBehaviorProvider } from 'humanbehavior-js/react'

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

Step 3: Using the Tracker in Your Components

Track Custom Events

Use the built-in useHumanBehavior hook to track custom events:
import React, { useEffect } from 'react'
import { useHumanBehavior } from 'humanbehavior-js/react'

export default function MyComponent() {
  const tracker = useHumanBehavior()

  useEffect(() => {
    // Track a custom event when component loads
    tracker.customEvent('component_viewed', {
      componentName: 'MyComponent',
      timestamp: new Date().toISOString()
    })
  }, [tracker])

  const handleButtonClick = async () => {
    await tracker.customEvent('special_button_clicked', {
      buttonLocation: 'header',
      userAction: 'clicked_cta'
    })
    
    // Your other button logic here
  }

  return (
    <div>
      <h1>My Component</h1>
      <button onClick={handleButtonClick}>
        Click Me
      </button>
    </div>
  )
}

Automatic Page View Tracking

Good news! The HumanBehaviorProvider automatically tracks page views for you. It handles:
  • Initial page loads
  • Route changes (pushState/replaceState)
  • Back/forward navigation (popstate)
  • Hash changes
No additional setup required! Page views are tracked automatically when you use the provider. If you need to manually track a page view for some reason, you can still do it:
import React from 'react'
import { useHumanBehavior } from 'humanbehavior-js/react'

export default function CustomPageView() {
  const tracker = useHumanBehavior()

  const handleCustomPageView = () => {
    // Track a custom page view
    tracker.trackPageView('/custom-page')
  }

  return (
    <button onClick={handleCustomPageView}>
      Track Custom Page View
    </button>
  )
}

Step 4: Advanced Usage

User Authentication

Use the built-in useUserTracking hook to track user information:
import React, { useState } from 'react'
import { useUserTracking } from 'humanbehavior-js/react'

export default function LoginForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const { addUserInfo } = useUserTracking()

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // Your login logic here
    const user = await login(email, password)
    
    // Track user info with HumanBehavior
    if (user) {
      const result = await addUserInfo(user.id, {
        email: user.email,
        name: user.name,
        plan: user.plan,
        signupDate: user.signupDate
      })
      
      if (result.success) {
        console.log('User info tracked successfully')
      } else {
        console.error('Failed to track user info:', result.error)
      }
    }
  }

  return (
    <form onSubmit={handleLogin}>
      <input 
        type="email" 
        value={email} 
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input 
        type="password" 
        value={password} 
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <button type="submit">Login</button>
    </form>
  )
}

Environment Variables

Store your API key securely using environment variables:
  1. Create a .env file in your project root:
REACT_APP_HUMANBEHAVIOR_API_KEY=your-api-key-here
  1. Update your App component to use the environment variable:
import React from 'react'
import { HumanBehaviorProvider } from 'humanbehavior-js/react'

function App() {
  const apiKey = process.env.REACT_APP_HUMANBEHAVIOR_API_KEY
  
  if (!apiKey) {
    console.error('HumanBehavior API key is missing')
    return <YourApp />
  }

  return (
    <HumanBehaviorProvider 
      apiKey={apiKey}
      options={{
        logLevel: process.env.NODE_ENV === 'development' ? 'debug' : 'error'
      }}
    >
      <YourApp />
    </HumanBehaviorProvider>
  )
}

Step 5: TypeScript Support

If you’re using TypeScript, add this to your types/global.d.ts file:
import { HumanBehaviorTracker } from 'humanbehavior-js'

declare global {
  interface Window {
    __humanBehaviorGlobalTracker?: HumanBehaviorTracker
  }
}

Available Built-in Hooks

The HumanBehaviorTracker comes with several built-in hooks:

1. useHumanBehavior

Main hook for tracking events and accessing the tracker:
import React from 'react'
import { useHumanBehavior } from 'humanbehavior-js/react'

export default function MyComponent() {
  const tracker = useHumanBehavior()

  const handleClick = async () => {
    await tracker.customEvent('button_clicked', { 
      location: 'header',
      timestamp: Date.now()
    })
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  )
}

2. useUserTracking

Hook for managing user information:
import React from 'react'
import { useUserTracking } from 'humanbehavior-js/react'

export default function UserProfile() {
  const { addUserInfo } = useUserTracking()

  const handleUpdateProfile = async (userData: any) => {
    const result = await addUserInfo(userData.id, {
      name: userData.name,
      email: userData.email,
      plan: userData.plan
    })
    
    if (result.success) {
      console.log('User info updated successfully')
    }
  }

  return (
    <button onClick={() => handleUpdateProfile({ /* user data */ })}>
      Update Profile
    </button>
  )
}

3. useRedaction

Hook for managing field redaction:
import React from 'react'
import { useRedaction } from 'humanbehavior-js/react'

export default function PrivacySettings() {
  const { setRedactedFields, isRedactionActive, getRedactedFields } = useRedaction()

  const handleEnableRedaction = () => {
    setRedactedFields([
      'input[type="password"]',
      'input[name="ssn"]',
      '.sensitive-data'
    ])
  }

  const handleDisableRedaction = () => {
    setRedactedFields([])
  }

  return (
    <div>
      <p>Redaction active: {isRedactionActive() ? 'Yes' : 'No'}</p>
      <p>Redacted fields: {getRedactedFields().join(', ')}</p>
      <button onClick={handleEnableRedaction}>Enable Redaction</button>
      <button onClick={handleDisableRedaction}>Disable Redaction</button>
    </div>
  )
}

React-Specific Features

Event Queuing

The React integration includes intelligent event queuing. If you try to track events before the tracker is fully initialized, they’ll be queued and processed once initialization is complete:
import React, { useEffect } from 'react'
import { useHumanBehavior } from 'humanbehavior-js/react'

export default function EarlyEventTracking() {
  const tracker = useHumanBehavior()

  useEffect(() => {
    // This event will be queued if tracker isn't ready yet
    tracker.customEvent('early_event', { 
      timestamp: Date.now() 
    })
  }, [tracker])

  return <div>Component with early event tracking</div>
}

Server-Side Rendering (SSR) Support

The React integration is SSR-safe and handles server-side rendering gracefully:
import React from 'react'
import { HumanBehaviorProvider } from 'humanbehavior-js/react'

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

// The provider automatically detects server-side rendering
// and only initializes the tracker on the client side

Custom Hook Patterns

Create custom hooks to encapsulate tracking logic:
import { useCallback } from 'react'
import { useHumanBehavior } from 'humanbehavior-js/react'

export function useTracking() {
  const tracker = useHumanBehavior()
  
  const trackButtonClick = useCallback(async (buttonId: string, additionalProps = {}) => {
    await tracker.customEvent('button_clicked', {
      buttonId,
      timestamp: Date.now(),
      ...additionalProps
    })
  }, [tracker])
  
  const trackFormSubmit = useCallback(async (formId: string, fields: string[]) => {
    await tracker.customEvent('form_submitted', {
      formId,
      fields,
      timestamp: Date.now()
    })
  }, [tracker])
  
  return {
    trackButtonClick,
    trackFormSubmit,
    tracker // Access to full tracker instance
  }
}

// Usage
export default function MyComponent() {
  const { trackButtonClick, trackFormSubmit } = useTracking()
  
  const handleSubmit = async (formData: any) => {
    await trackFormSubmit('contact-form', ['name', 'email', 'message'])
    // Submit form logic
  }
  
  return (
    <form onSubmit={handleSubmit}>
      <button onClick={() => trackButtonClick('submit-btn')}>
        Submit
      </button>
    </form>
  )
}

Troubleshooting

Common Issues

  1. “useHumanBehavior must be used within a HumanBehaviorProvider” error
    • Make sure your component is wrapped with HumanBehaviorProvider
    • Check that the provider is higher up in the component tree
  2. Tracker not working
    • Check the browser console for any error messages
    • Verify your API key is correct
    • Make sure the provider is properly initialized
  3. Events not being tracked
    • Make sure the tracker is initialized before trying to track events
    • Check that you’re using the correct tracker instance
    • Verify that events are being queued properly

Debug Mode

Enable debug mode to see what’s happening by setting the logLevel in the provider options:
<HumanBehaviorProvider 
  apiKey="your-api-key-here"
  options={{
    logLevel: 'debug' // This will show detailed logs in the console
  }}
>
  {children}
</HumanBehaviorProvider>

Check Connection

Test if the tracker can connect to the server:
import React, { useEffect } from 'react'
import { useHumanBehavior } from 'humanbehavior-js/react'

export default function ConnectionTest() {
  const tracker = useHumanBehavior()

  useEffect(() => {
    if (tracker) {
      tracker.testConnection().then((result) => {
        if (result.success) {
          console.log('✅ HumanBehavior connection successful')
        } else {
          console.error('❌ HumanBehavior connection failed:', result.error)
        }
      })
    }
  }, [tracker])

  return null
}