The churn radar for B2B SaaS·Book a call·Setup in 10 minutes·Trusted by CS teams·SOC 2 · GDPR · AES-256·
The churn radar for B2B SaaS·Book a call·Setup in 10 minutes·Trusted by CS teams·SOC 2 · GDPR · AES-256·

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)
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, page_viewed)
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
  • page_viewed — Page navigation
  • milestone_reached — Important milestones

Usesetup

Convenience hook that returns just the setup function.

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

function LoginHandler() {
  const setup = useSetup()

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

  return <button onClick={() => onLogin(user, org)}>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, organization }) {
  useFirstDistroSetup({
    userId: user.id,
    userEmail: user.email,
    userName: user.name,
    accountId: organization.id,
    accountName: organization.name,
    accountPlan: organization.plan,
  })

  return null // Render nothing, just sets context
}

Setupoptions

PropertyTypeRequiredDescription
userIdstringYesUnique user identifier
userEmailstringNoUser's email address
userNamestringNoUser's display name
userPropertiesobjectNoAdditional user properties
accountIdstringNo*Account/organization ID
accountNamestringNoAccount/organization name
accountPlanstringNoAccount plan (e.g., free, pro, enterprise)
accountPropertiesobjectNoAdditional account properties

Note: While accountId is technically optional, it's required for Customer Insights to work. Without account context, events are stored but health scores won't be calculated.

Conditional setup

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

tsx
function UserIdentifier({ user, organization }) {
  // Only set up when both user and organization are loaded
  useFirstDistroSetup(
    user && organization
      ? {
          userId: user.id,
          userEmail: user.email,
          accountId: organization.id,
          accountName: organization.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 accountId is set (required for Customer Insights)
  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.