React hooks reference

Complete reference for FirstDistro React hooks including FirstDistroProvider, useTrack, useSetup, and useFirstDistroSetup.

The @firstdistro/sdk/react package provides React-specific hooks for easy integration with your React or Next.js app.

Installation

bash
npm install @firstdistro/sdk

Firstdistroprovider

Wrap your app with FirstDistroProvider to initialize the SDK.

tsx
import { FirstDistroProvider } from '@firstdistro/sdk/react'

function App() {
  return (
    <FirstDistroProvider
      token={process.env.NEXT_PUBLIC_FIRSTDISTRO_TOKEN!}
      onReady={() => console.log('SDK ready')}
      onError={(err) => console.error('SDK error:', err)}
    >
      {children}
    </FirstDistroProvider>
  )
}

Props

PropTypeRequiredDescription
tokenstringYesYour installation token (starts with fd_)
apiUrlstringNoCustom API URL (defaults to https://firstdistro.com)
autoCapturebooleanNoAuto-capture $pageview on load and SPA route changes (defaults to true)
captureQueryParamsstring[]NoAllowlist of query-param names to keep on captured URLs. Query strings are stripped by default for PII safety
maskUrl(url: string) => string | nullNoHook applied to each captured $pageview URL after the default strip. Return a string to replace the URL, or null to drop the capture entirely (npm install only)
onReady() => voidNoCalled when SDK is initialized and ready
onError(error: Error) => voidNoCalled if SDK initialization fails

Usefirstdistro

Access the full SDK context. Returns all available methods and state.

tsx
import { useFirstDistro } from '@firstdistro/sdk/react'

function MyComponent() {
  const { track, setup, reset, isReady, error } = useFirstDistro()

  if (error) {
    return <div>SDK Error: {error.message}</div>
  }

  if (!isReady) {
    return <div>Loading...</div>
  }

  return <button onClick={() => track('clicked')}>Click me</button>
}

Return value

PropertyTypeDescription
track(eventName: string, properties?: object) => voidTrack a custom event
setup(options: SetupOptions) => voidSet user and account context
reset() => voidClear all user/account context (call on logout)
isReadybooleanWhether the SDK has finished initializing
errorError | nullAny initialization error

Usetrack

Convenience hook that returns just the track function.

tsx
import { useTrack } from '@firstdistro/sdk/react'

function ExportButton() {
  const track = useTrack()

  return (
    <button onClick={() => track('feature_used', { feature: 'export' })}>
      Export
    </button>
  )
}

Parameters

ParameterTypeRequiredDescription
eventNamestringYesName of the event (e.g., feature_used, milestone_reached)
propertiesobjectNoAdditional event properties

Event naming conventions

Use snake_case for event names:

  • user_signed_up — New user registration
  • user_logged_in — User login
  • feature_used — Feature interaction
  • milestone_reached — Important milestones

Page navigation is captured automatically as $pageview after setup() — you don't need to track it manually.


Usesetup

Convenience hook that returns just the setup function.

tsx
import { useSetup } from '@firstdistro/sdk/react'

function LoginHandler() {
  const setup = useSetup()

  const onLogin = (user) => {
    setup({
      userId: user.id,
      userEmail: user.email,
    })
  }

  return <button onClick={() => onLogin(user)}>Login</button>
}

Usefirstdistrosetup

Hook that automatically calls setup() when component mounts or when options change. Best for setting context once user data is available.

tsx
import { useFirstDistroSetup } from '@firstdistro/sdk/react'

function UserIdentifier({ user }) {
  useFirstDistroSetup({
    userId: user.id,
    userEmail: user.email,
    userName: user.name,
  })

  return null // Render nothing, just sets context
}

Setupoptions

PropertyTypeRequiredDescription
userIdstringYesUnique user identifier
userEmailstringYesUser email — server derives account from domain
userNamestringNoUser's display name
userPropertiesobjectNoAdditional user properties
accountIdstringNoOptional override for multi-domain orgs
accountNamestringNoAccount name (with explicit accountId)
accountPlanstringNoAccount plan (with explicit accountId)
accountPropertiesobjectNoAdditional account properties

Note: Do not use deprecated identify() / group() — use setup() only. accountId is optional; email is enough for typical Customer Insights installs.

Conditional setup

Pass null to skip setup (useful when user data isn't loaded yet):

tsx
function UserIdentifier({ user }) {
  useFirstDistroSetup(
    user?.id && user?.email
      ? {
          userId: user.id,
          userEmail: user.email,
          userName: user.name,
        }
      : null
  )

  return null
}

Handling logout

Call reset() when users log out to clear their context:

tsx
import { useFirstDistro } from '@firstdistro/sdk/react'

function LogoutButton() {
  const { reset } = useFirstDistro()

  const handleLogout = () => {
    reset() // Clear FirstDistro context first
    signOut() // Then sign out
  }

  return <button onClick={handleLogout}>Logout</button>
}

Warning: Without calling reset(), the next user who logs in may inherit the previous user's context, polluting your analytics.


Typescript support

All hooks and components are fully typed. Import types as needed:

tsx
import type {
  SetupOptions,
  TrackProperties,
  FirstDistroContextValue,
  FirstDistroProviderProps,
} from '@firstdistro/sdk/react'

Complete example

tsx
// app/providers.tsx
'use client'

import { FirstDistroProvider } from '@firstdistro/sdk/react'

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <FirstDistroProvider token={process.env.NEXT_PUBLIC_FIRSTDISTRO_TOKEN!}>
      {children}
    </FirstDistroProvider>
  )
}

// app/components/UserContext.tsx
'use client'

import { useFirstDistroSetup } from '@firstdistro/sdk/react'
import { useUser } from './auth' // Your auth hook

export function UserContext() {
  const { user, organization } = useUser()

  useFirstDistroSetup(
    user && organization
      ? {
          userId: user.id,
          userEmail: user.email,
          userName: user.name,
          accountId: organization.id,
          accountName: organization.name,
          accountPlan: organization.plan,
        }
      : null
  )

  return null
}

// app/components/FeatureButton.tsx
'use client'

import { useTrack } from '@firstdistro/sdk/react'

export function FeatureButton({ feature }: { feature: string }) {
  const track = useTrack()

  return (
    <button onClick={() => track('feature_used', { feature })}>
      Use {feature}
    </button>
  )
}

Troubleshooting

"usefirstdistro must be used within a firstdistroprovider"

Ensure your component tree is wrapped with FirstDistroProvider:

tsx
// Correct
<FirstDistroProvider token="...">
  <MyComponent /> {/* Can use hooks here */}
</FirstDistroProvider>

// Wrong
<MyComponent /> {/* Hooks will throw error */}

Events not appearing in dashboard

  1. Check isReady is true before tracking
  2. Verify your token is correct
  3. Ensure userEmail is set in setup (required for account derivation)
  4. Check browser console for errors

Sdk initializing multiple times

The provider handles cleanup automatically. If you see multiple initializations, ensure you're not mounting/unmounting the provider unnecessarily.