@achado/react
v0.0.2
Published
React bindings for Achado analytics SDK
Downloads
16
Maintainers
Readme
@achado/react
React bindings for Achado analytics SDK. This package provides React hooks and components that make it easy to integrate Achado analytics into React applications.
Installation
npm install @achado/react
# or
pnpm add @achado/react
# or
yarn add @achado/reactPeer Dependencies: This package requires React 16.8+ (for hooks support).
Quick Start
1. Provider Setup
Wrap your app with the AchadoProvider:
import { AchadoProvider } from '@achado/react';
function App() {
return (
<AchadoProvider
config={{
apiKey: 'your-api-key-here',
debug: true,
}}
loadingComponent={<div>Loading analytics...</div>}
>
<YourApp />
</AchadoProvider>
);
}2. Using Hooks
import { useAchadoTracking, useAchadoUser } from '@achado/react';
function UserProfile() {
const { track, trackClick } = useAchadoTracking();
const { user, identify } = useAchadoUser();
const handleSignUp = async (userData) => {
// Identify the user
identify(userData.id, {
name: userData.name,
email: userData.email,
plan: 'free',
});
// Track the signup event
track('user_signed_up', {
source: 'profile_page',
plan: userData.plan,
});
};
return (
<div>
<h1>Welcome, {user?.traits?.name || 'Guest'}!</h1>
<button onClick={() => trackClick('upgrade_button')}>Upgrade Plan</button>
</div>
);
}API Reference
Components
AchadoProvider
Provides Achado client context to child components.
import { AchadoProvider } from '@achado/react';
// Option 1: Configuration-based (recommended)
<AchadoProvider
config={{
apiKey: 'your-api-key',
debug: true,
userId: 'user-123', // optional
}}
loadingComponent={<LoadingSpinner />}
errorComponent={<ErrorMessage />}
>
<App />
</AchadoProvider>
// Option 2: Client-based (advanced)
<AchadoProvider
client={existingClient}
loadingComponent={<LoadingSpinner />}
>
<App />
</AchadoProvider>Props:
config: AchadoConfig- Achado configuration (alternative to client)client: AchadoClient- Pre-initialized client (alternative to config)loadingComponent?: ReactNode- Component shown while initializingerrorComponent?: ReactNode- Component shown on initialization errorchildren: ReactNode- Your app components
Hooks
useAchadoClient()
Access the raw Achado client and core methods.
import { useAchadoClient } from '@achado/react';
function MyComponent() {
const {
client, // Raw AchadoClient instance
track, // Track custom events
identify, // Identify users
setUserProperties, // Set user properties
getUser, // Get current user
flush, // Flush pending events
reset, // Reset client state
getQueueStats, // Get queue statistics
isLoading, // Loading state
isInitialized, // Initialization state
} = useAchadoClient();
return <div>Status: {isLoading ? 'Loading...' : 'Ready'}</div>;
}useAchadoTracking()
Convenient tracking methods for common events.
import { useAchadoTracking } from '@achado/react';
function MyComponent() {
const {
track, // Track any event
trackPageView, // Track page views
trackClick, // Track clicks
trackConversion, // Track conversions
trackError, // Track errors
getTrackingCallback, // Get memoized callback
} = useAchadoTracking();
const handleClick = getTrackingCallback('button_clicked', {
button_id: 'header-cta',
location: 'top-nav',
});
return <button onClick={handleClick}>Click me!</button>;
}useAchadoUser()
User identification and management.
import { useAchadoUser } from '@achado/react';
function UserProfile() {
const {
user, // Current user data
identify, // Identify user
setUserProperties, // Set user properties
updateTraits, // Update user traits
resetUser, // Reset user data
getUserProperty, // Get specific property
getUserTrait, // Get specific trait
isIdentified, // Is user identified?
sessionId, // Current session ID
anonymousId, // Anonymous ID
} = useAchadoUser();
if (!isIdentified) {
return <LoginForm onLogin={identify} />;
}
return (
<div>
<h1>Hello, {getUserTrait('name')}!</h1>
<p>Session: {sessionId}</p>
</div>
);
}useAchadoAnalytics()
Analytics utilities and statistics.
import { useAchadoAnalytics } from '@achado/react';
function AnalyticsDashboard() {
const {
getStats, // Get analytics stats
flush, // Flush pending events
getQueueStats, // Get queue stats
isReady, // Is client ready?
sdkVersion, // SDK version
setDebugMode, // Enable/disable debug
} = useAchadoAnalytics();
const stats = getStats();
return (
<div>
<h2>Analytics Status</h2>
<p>Ready: {isReady ? 'Yes' : 'No'}</p>
<p>SDK Version: {sdkVersion}</p>
<p>Pending Events: {stats.queueStats.pending}</p>
<button onClick={() => flush()}>Flush Events</button>
</div>
);
}Advanced Usage
Server-Side Rendering (SSR)
The React bindings handle SSR gracefully by deferring client initialization to the browser:
// Next.js example
import { AchadoProvider } from '@achado/react';
function MyApp({ Component, pageProps }) {
return (
<AchadoProvider
config={{
apiKey: process.env.NEXT_PUBLIC_ACHADO_API_KEY,
debug: process.env.NODE_ENV === 'development',
}}
loadingComponent={<div>Initializing analytics...</div>}
>
<Component {...pageProps} />
</AchadoProvider>
);
}Custom Hook Composition
Create your own specialized hooks:
import { useAchadoTracking, useAchadoUser } from '@achado/react';
function useEcommerceTracking() {
const { track } = useAchadoTracking();
const { user } = useAchadoUser();
const trackPurchase = (orderData) => {
track('purchase', {
order_id: orderData.id,
total: orderData.total,
currency: orderData.currency,
user_id: user?.userId,
});
};
const trackAddToCart = (product) => {
track('add_to_cart', {
product_id: product.id,
product_name: product.name,
price: product.price,
});
};
return { trackPurchase, trackAddToCart };
}Error Boundaries
Handle analytics errors gracefully:
import { AchadoProvider } from '@achado/react';
function App() {
return (
<AchadoProvider
config={{ apiKey: 'your-api-key' }}
errorComponent={
<div>Analytics failed to load. App will continue without tracking.</div>
}
>
<YourApp />
</AchadoProvider>
);
}TypeScript Support
This package includes full TypeScript definitions:
import type {
AchadoConfig,
AchadoUser,
AchadoProviderProps,
UseAchadoTrackingOutput,
UseAchadoUserOutput,
UseAchadoAnalyticsOutput,
} from '@achado/react';
// All hooks and components are fully typed
const trackingHook: UseAchadoTrackingOutput = useAchadoTracking();Best Practices
1. Provider Placement
Place the AchadoProvider as high as possible in your component tree:
// ✅ Good - High in the tree
<AchadoProvider config={config}>
<Router>
<App />
</Router>
</AchadoProvider>
// ❌ Avoid - Too low, limits hook usage
<App>
<AchadoProvider config={config}>
<SomeComponent />
</AchadoProvider>
</App>2. Loading States
Always provide loading components for better UX:
<AchadoProvider config={config} loadingComponent={<SkeletonLoader />}>
<App />
</AchadoProvider>3. Event Batching
The SDK automatically batches events, but you can manually flush when needed:
function usePageTransition() {
const { flush } = useAchadoAnalytics();
useEffect(() => {
// Flush events before page unload
const handleBeforeUnload = () => {
flush();
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => window.removeEventListener('beforeunload', handleBeforeUnload);
}, [flush]);
}Examples
- Basic React App (coming soon)
- Next.js Integration (coming soon)
- E-commerce Tracking (coming soon)
Migration Guide
Migrating from direct client usage:
// Before (direct client)
import { AchadoClient } from '@achado/client';
const client = new AchadoClient({ apiKey: 'key' });
await client.initialize();
client.track('event');
// After (React bindings)
import { AchadoProvider, useAchadoTracking } from '@achado/react';
function App() {
return (
<AchadoProvider config={{ apiKey: 'key' }}>
<MyComponent />
</AchadoProvider>
);
}
function MyComponent() {
const { track } = useAchadoTracking();
useEffect(() => {
track('event');
}, []);
}License
MIT
