> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/AslamSDM/mentiq-sdk/llms.txt
> Use this file to discover all available pages before exploring further.

# useOnboardingTracker

> Track user onboarding progress through multi-step flows

## Overview

The `useOnboardingTracker` hook creates an `OnboardingTracker` instance that helps track user progress through onboarding flows. It provides methods for starting, completing, skipping steps, and monitoring overall progress.

## Usage

```tsx theme={null}
import { useOnboardingTracker } from 'mentiq-sdk';
import { useAnalytics } from 'mentiq-sdk';

function OnboardingFlow() {
  const { analytics } = useAnalytics();
  const tracker = useOnboardingTracker(analytics, {
    steps: [
      { name: 'create_account', index: 0, required: true },
      { name: 'add_profile', index: 1, required: true },
      { name: 'invite_team', index: 2, required: false },
      { name: 'complete_tutorial', index: 3, required: false }
    ]
  });

  const handleStepComplete = (stepName: string) => {
    tracker?.completeStep(stepName, { timestamp: Date.now() });
  };

  return (
    <div>
      <button onClick={() => tracker?.start()}>Start Onboarding</button>
      <button onClick={() => handleStepComplete('create_account')}>
        Complete Account Creation
      </button>
    </div>
  );
}
```

## Parameters

<ParamField path="analytics" type="Analytics | null" required>
  The analytics instance from `useAnalytics()`. Returns `null` if analytics is not available.
</ParamField>

<ParamField path="config" type="OnboardingConfig" required>
  Configuration object for the onboarding flow

  <ParamField path="config.steps" type="OnboardingStep[]" required>
    Array of onboarding steps

    Each step has:

    * `name` (string): Unique identifier for the step
    * `index` (number): Order of the step (0-based)
    * `required` (boolean, optional): Whether step is required for completion
  </ParamField>

  <ParamField path="config.autoTrack" type="boolean">
    Whether to automatically track step progression (not currently implemented)
  </ParamField>
</ParamField>

## Returns

<ResponseField name="OnboardingTracker | null" type="object">
  Returns an `OnboardingTracker` instance with the following methods, or `null` if analytics is unavailable.
</ResponseField>

## Methods

### start()

Start the onboarding process and track the "onboarding\_started" event.

**Signature:** `start(properties?: Record<string, any>): void`

```tsx theme={null}
tracker?.start({
  source: 'signup_page',
  user_type: 'free_trial'
});
```

**Tracked Event:** `"onboarding_started"`

* `total_steps`: Number of steps in the flow
* Any additional properties passed

### completeStep()

Mark a step as completed and track progress.

**Signature:** `completeStep(stepName: string, properties?: Record<string, any>): void`

```tsx theme={null}
tracker?.completeStep('create_account', {
  account_type: 'business',
  signup_method: 'google'
});
```

**Tracked Event:** `"onboarding_step_completed"`

* `step_name`: Name of the completed step
* `step_index`: Index of the step
* `required`: Whether the step was required
* `steps_completed`: Total steps completed so far
* `total_steps`: Total steps in the flow
* `progress`: Completion percentage (0-100)
* `time_since_start`: Milliseconds since onboarding started
* Any additional properties passed

### skipStep()

Skip an optional step (only works for non-required steps).

**Signature:** `skipStep(stepName: string, reason?: string): void`

```tsx theme={null}
tracker?.skipStep('invite_team', 'will_do_later');
```

**Tracked Event:** `"onboarding_step_skipped"`

* `step_name`: Name of the skipped step
* `step_index`: Index of the step
* `reason`: Reason for skipping (defaults to "not\_specified")
* `steps_completed`: Steps completed so far
* `total_steps`: Total steps in the flow

<Warning>
  Attempting to skip a required step will log a warning and not track the event.
</Warning>

### complete()

Mark the entire onboarding flow as complete.

**Signature:** `complete(properties?: Record<string, any>): void`

```tsx theme={null}
tracker?.complete({
  completion_quality: 'full',
  features_enabled: ['analytics', 'alerts']
});
```

**Tracked Event:** `"onboarding_completed"`

* `steps_completed`: Total steps completed
* `total_steps`: Total steps in the flow
* `completion_rate`: Percentage of steps completed (0-100)
* `duration_ms`: Total time in milliseconds
* `duration_seconds`: Total time in seconds
* Any additional properties passed

### abandon()

Mark onboarding as abandoned and track where the user dropped off.

**Signature:** `abandon(reason?: string): void`

```tsx theme={null}
tracker?.abandon('too_complex');
```

**Tracked Event:** `"onboarding_abandoned"`

* `step_name`: Current step where user abandoned
* `step_index`: Index of current step
* `steps_completed`: Steps completed before abandoning
* `total_steps`: Total steps in flow
* `progress`: Completion percentage when abandoned
* `duration_ms`: Time spent before abandoning
* `reason`: Reason for abandoning (defaults to "not\_specified")

### getProgress()

Get current onboarding progress.

**Signature:** `getProgress(): ProgressObject`

```tsx theme={null}
const progress = tracker?.getProgress();
console.log(`${progress?.progressPercent}% complete`);
```

**Returns:**

```typescript theme={null}
{
  currentStep: string | null;         // Current step name
  currentStepIndex: number;           // Current step index
  completedSteps: string[];           // Array of completed step names
  totalSteps: number;                 // Total number of steps
  progressPercent: number;            // Completion percentage (0-100)
  duration: number | null;            // Time elapsed in ms, or null if not started
}
```

### isStepCompleted()

Check if a specific step has been completed.

**Signature:** `isStepCompleted(stepName: string): boolean`

```tsx theme={null}
if (tracker?.isStepCompleted('create_account')) {
  // Show next step
}
```

### reset()

Reset the tracker to initial state.

**Signature:** `reset(): void`

```tsx theme={null}
tracker?.reset(); // Clear all progress
```

## Type Definitions

### OnboardingConfig

```typescript theme={null}
interface OnboardingConfig {
  steps: OnboardingStep[];
  autoTrack?: boolean;
}
```

### OnboardingStep

```typescript theme={null}
interface OnboardingStep {
  name: string;
  index: number;
  required?: boolean;
}
```

## Examples

### Multi-Step Wizard

```tsx theme={null}
import { useOnboardingTracker } from 'mentiq-sdk';
import { useAnalytics } from 'mentiq-sdk';
import { useState } from 'react';

function OnboardingWizard() {
  const { analytics } = useAnalytics();
  const [currentStep, setCurrentStep] = useState(0);
  
  const tracker = useOnboardingTracker(analytics, {
    steps: [
      { name: 'welcome', index: 0, required: true },
      { name: 'profile', index: 1, required: true },
      { name: 'preferences', index: 2, required: false },
      { name: 'finish', index: 3, required: true }
    ]
  });

  const handleNext = () => {
    const stepName = tracker?.getProgress().currentStep;
    if (stepName) {
      tracker?.completeStep(stepName);
    }
    setCurrentStep(prev => prev + 1);
  };

  const handleSkip = () => {
    const stepName = tracker?.getProgress().currentStep;
    if (stepName) {
      tracker?.skipStep(stepName, 'user_skipped');
    }
    setCurrentStep(prev => prev + 1);
  };

  React.useEffect(() => {
    if (currentStep === 0) {
      tracker?.start({ source: 'app_launch' });
    }
  }, [tracker]);

  return (
    <div>
      <StepContent step={currentStep} />
      <button onClick={handleNext}>Next</button>
      <button onClick={handleSkip}>Skip</button>
    </div>
  );
}
```

### Progress Bar Display

```tsx theme={null}
import { useOnboardingTracker } from 'mentiq-sdk';
import { useAnalytics } from 'mentiq-sdk';

function OnboardingProgress() {
  const { analytics } = useAnalytics();
  const tracker = useOnboardingTracker(analytics, config);
  const progress = tracker?.getProgress();

  return (
    <div>
      <div className="progress-bar">
        <div 
          className="progress-fill" 
          style={{ width: `${progress?.progressPercent || 0}%` }}
        />
      </div>
      <p>
        Step {(progress?.currentStepIndex || 0) + 1} of {progress?.totalSteps}
      </p>
      <p>{progress?.progressPercent.toFixed(0)}% Complete</p>
    </div>
  );
}
```

### Conditional Step Logic

```tsx theme={null}
import { useOnboardingTracker } from 'mentiq-sdk';
import { useAnalytics } from 'mentiq-sdk';

function SmartOnboarding() {
  const { analytics } = useAnalytics();
  const tracker = useOnboardingTracker(analytics, config);

  const handleUserAction = (action: string) => {
    if (action === 'upgrade_to_premium') {
      // Skip free tier onboarding steps
      tracker?.skipStep('free_trial_intro', 'upgraded_to_premium');
      tracker?.completeStep('select_premium_plan');
    }
  };

  return (
    <div>
      {!tracker?.isStepCompleted('select_plan') && (
        <PlanSelection onSelect={handleUserAction} />
      )}
    </div>
  );
}
```

## Automatic Completion

<Info>
  When all steps are completed (via `completeStep()`), the tracker automatically calls `complete()` to track the "onboarding\_completed" event.
</Info>

## Notes

<Tip>
  Track granular step completion to understand where users drop off in your onboarding flow. Use the `abandon()` method to explicitly track when users exit the flow.
</Tip>

<Warning>
  Required steps cannot be skipped. Attempting to skip a required step will log a console warning and no event will be tracked.
</Warning>

<Note>
  The tracker maintains state in memory. If you need persistence across page refreshes, store progress in localStorage or your backend.
</Note>

## Related Hooks

* [useAnalytics](/api/hooks/use-analytics) - Required to get the analytics instance
* [useSessionTracking](/api/hooks/use-session-tracking) - Track session metrics during onboarding
