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
npm install @firstdistro/sdk
Firstdistroprovider
Wrap your app with FirstDistroProvider to initialize the SDK.
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
| Prop | Type | Required | Description |
|---|---|---|---|
token | string | Yes | Your installation token (starts with fd_) |
apiUrl | string | No | Custom API URL (defaults to https://firstdistro.com) |
autoCapture | boolean | No | Auto-capture $pageview on load and SPA route changes (defaults to true) |
captureQueryParams | string[] | No | Allowlist of query-param names to keep on captured URLs. Query strings are stripped by default for PII safety |
maskUrl | (url: string) => string | null | No | Hook 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 | () => void | No | Called when SDK is initialized and ready |
onError | (error: Error) => void | No | Called if SDK initialization fails |
Usefirstdistro
Access the full SDK context. Returns all available methods and state.
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
| Property | Type | Description |
|---|---|---|
track | (eventName: string, properties?: object) => void | Track a custom event |
setup | (options: SetupOptions) => void | Set user and account context |
reset | () => void | Clear all user/account context (call on logout) |
isReady | boolean | Whether the SDK has finished initializing |
error | Error | null | Any initialization error |
Usetrack
Convenience hook that returns just the track function.
import { useTrack } from '@firstdistro/sdk/react'
function ExportButton() {
const track = useTrack()
return (
<button onClick={() => track('feature_used', { feature: 'export' })}>
Export
</button>
)
}
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
eventName | string | Yes | Name of the event (e.g., feature_used, milestone_reached) |
properties | object | No | Additional event properties |
Event naming conventions
Use snake_case for event names:
user_signed_up— New user registrationuser_logged_in— User loginfeature_used— Feature interactionmilestone_reached— Important milestones
Page navigation is captured automatically as
$pageviewaftersetup()— you don't need to track it manually.
Usesetup
Convenience hook that returns just the setup function.
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.
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
| Property | Type | Required | Description |
|---|---|---|---|
userId | string | Yes | Unique user identifier |
userEmail | string | Yes | User email — server derives account from domain |
userName | string | No | User's display name |
userProperties | object | No | Additional user properties |
accountId | string | No | Optional override for multi-domain orgs |
accountName | string | No | Account name (with explicit accountId) |
accountPlan | string | No | Account plan (with explicit accountId) |
accountProperties | object | No | Additional 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):
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:
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:
import type {
SetupOptions,
TrackProperties,
FirstDistroContextValue,
FirstDistroProviderProps,
} from '@firstdistro/sdk/react'
Complete example
// 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:
// Correct
<FirstDistroProvider token="...">
<MyComponent /> {/* Can use hooks here */}
</FirstDistroProvider>
// Wrong
<MyComponent /> {/* Hooks will throw error */}
Events not appearing in dashboard
- Check
isReadyistruebefore tracking - Verify your token is correct
- Ensure
userEmailis set in setup (required for account derivation) - 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.