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.
Overview
Performance tracking captures critical metrics about page load times, rendering performance, and user experience. The SDK automatically tracks Core Web Vitals and provides tools for custom performance measurements.
Quick Start
Enable Performance Tracking
Set enablePerformanceTracking: true in your analytics configuration:import { AnalyticsProvider } from "mentiq-sdk";
function App() {
return (
<AnalyticsProvider
config={{
apiKey: "your-api-key",
projectId: "your-project-id",
enablePerformanceTracking: true,
}}
>
<YourApp />
</AnalyticsProvider>
);
}
Automatic Metrics Collection
Once enabled, the SDK automatically tracks:
- Page load time
- DOM ready time
- First Byte (TTFB)
- DNS lookup time
- First Paint (FP)
- First Contentful Paint (FCP)
View in Dashboard
Access performance metrics in your MentiQ dashboard to:
- Monitor Core Web Vitals trends
- Identify slow pages
- Compare performance across devices and browsers
- Set performance budgets and alerts
Core Web Vitals
The SDK automatically tracks Google’s Core Web Vitals when enablePerformanceTracking is enabled:
Largest Contentful Paint (LCP)
Measures loading performance. Good LCP is under 2.5 seconds.
Measures interactivity. Good FID is under 100 milliseconds.
Cumulative Layout Shift (CLS)
Measures visual stability. Good CLS is under 0.1.
First Contentful Paint (FCP)
Measures when the first content is rendered. Good FCP is under 1.8 seconds.
From src/analytics.ts:427-447, the SDK captures navigation timing automatically:
private setupPerformanceTracking(): void {
if ("performance" in window && "getEntriesByType" in performance) {
window.addEventListener("load", () => {
setTimeout(() => {
const navigation = performance.getEntriesByType(
"navigation"
)[0] as PerformanceNavigationTiming;
if (navigation) {
this.track("page_performance", {
load_time: navigation.loadEventEnd - navigation.fetchStart,
dom_ready: navigation.domContentLoadedEventEnd - navigation.fetchStart,
first_byte: navigation.responseStart - navigation.fetchStart,
dns_lookup: navigation.domainLookupEnd - navigation.domainLookupStart,
});
}
}, 0);
});
}
}
The SDK tracks these metrics automatically:
interface PerformanceData {
loadTime?: number; // Total page load time (ms)
domReady?: number; // DOM ready time (ms)
firstPaint?: number; // First Paint (ms)
firstContentfulPaint?: number; // First Contentful Paint (ms)
largestContentfulPaint?: number; // Largest Contentful Paint (ms)
firstInputDelay?: number; // First Input Delay (ms)
cumulativeLayoutShift?: number; // Cumulative Layout Shift score
timeToInteractive?: number; // Time to Interactive (ms)
}
Track custom performance metrics for specific operations:
Using the Hook
import { usePerformanceTracking } from "mentiq-sdk";
function DataLoadingComponent() {
const { measureCustomPerformance } = usePerformanceTracking();
useEffect(() => {
const measurement = measureCustomPerformance("fetch-user-data");
measurement.start();
fetchUserData().then(() => {
measurement.end(); // Automatically tracked to analytics
});
}, []);
return <UserProfile />;
}
Manual Tracking with Analytics Instance
import { useAnalytics } from "mentiq-sdk";
function SearchComponent() {
const { trackPerformance } = useAnalytics();
const handleSearch = async (query: string) => {
const startTime = performance.now();
const results = await searchAPI(query);
const duration = performance.now() - startTime;
trackPerformance({
searchDuration: duration,
resultCount: results.length,
});
};
return <SearchBar onSearch={handleSearch} />;
}
Track React component render performance with the PerformanceMonitor component:
import { PerformanceMonitor } from "mentiq-sdk";
function App() {
return (
<PerformanceMonitor
measureRender={true}
componentName="ProductList"
>
<ProductList products={products} />
</PerformanceMonitor>
);
}
This tracks:
- Initial render time
- Re-render frequency
- Total render duration
Use Cases
Track API Response Times
function useAPI() {
const { measureCustomPerformance } = usePerformanceTracking();
const fetchData = async (endpoint: string) => {
const measurement = measureCustomPerformance(`api-${endpoint}`);
measurement.start();
try {
const response = await fetch(endpoint);
const data = await response.json();
return data;
} finally {
measurement.end();
}
};
return { fetchData };
}
Monitor Image Load Times
function OptimizedImage({ src, alt }) {
const { measureCustomPerformance } = usePerformanceTracking();
useEffect(() => {
const measurement = measureCustomPerformance(`image-load-${src}`);
const img = new Image();
measurement.start();
img.onload = () => {
measurement.end();
};
img.src = src;
}, [src]);
return <img src={src} alt={alt} />;
}
Track Route Transitions
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { usePerformanceTracking } from "mentiq-sdk";
function RoutePerformanceTracker() {
const location = useLocation();
const { measureCustomPerformance } = usePerformanceTracking();
useEffect(() => {
const measurement = measureCustomPerformance(`route-${location.pathname}`);
measurement.start();
// Mark as complete when page is interactive
const timeout = setTimeout(() => {
measurement.end();
}, 100);
return () => clearTimeout(timeout);
}, [location.pathname]);
return null;
}
function useDatabaseQuery() {
const { trackPerformance } = useAnalytics();
const query = async (sql: string) => {
const startTime = performance.now();
const result = await db.execute(sql);
const duration = performance.now() - startTime;
trackPerformance({
queryDuration: duration,
queryType: sql.split(' ')[0], // SELECT, INSERT, etc.
rowCount: result.rows.length,
});
return result;
};
return { query };
}
From src/hooks.ts:174-234, the usePerformanceTracking hook provides:
const { measureCustomPerformance } = usePerformanceTracking();
// Returns an object with start() and end() methods
const measurement = measureCustomPerformance("operation-name");
measurement.start(); // Mark start time
// ... perform operation ...
measurement.end(); // Mark end time and send event
Internally, it uses the Performance API:
const measureCustomPerformance = useCallback(
(label: string) => {
if (typeof window === "undefined" || !("performance" in window)) return;
return {
start: () => performance.mark(`${label}-start`),
end: () => {
performance.mark(`${label}-end`);
performance.measure(label, `${label}-start`, `${label}-end`);
const measure = performance.getEntriesByName(label)[0];
if (measure) {
track("custom_performance", { [label]: measure.duration });
}
// Clean up marks and measures
performance.clearMarks(`${label}-start`);
performance.clearMarks(`${label}-end`);
performance.clearMeasures(label);
},
};
},
[track]
);
Set performance targets and track violations:
function App() {
const { trackPerformance } = useAnalytics();
useEffect(() => {
if ("performance" in window) {
const navigation = performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming;
const loadTime = navigation.loadEventEnd - navigation.fetchStart;
// Alert if page takes longer than 3 seconds
if (loadTime > 3000) {
trackPerformance({
budgetViolation: true,
loadTime: loadTime,
budgetThreshold: 3000,
});
}
}
}, []);
return <YourApp />;
}
Best Practices
Performance Tracking Tips:
- Enable performance tracking in production to get real user metrics
- Track both automatic Core Web Vitals and custom metrics
- Set performance budgets and monitor violations
- Segment performance by device type, connection speed, and geography
- Monitor performance trends over time, not just snapshots
What to Track
Always track:
- Core Web Vitals (automatic)
- API response times
- Critical user flows (checkout, signup)
- Resource load times (images, scripts)
Consider tracking:
- Component render times
- Database query performance
- Third-party script impact
- Route transition speed
Browser Compatibility
Performance tracking requires:
window.performance API (supported in all modern browsers)
PerformanceObserver for Core Web Vitals (IE11+)
PerformanceNavigationTiming for detailed metrics (Edge 12+)
The SDK gracefully degrades if these APIs are unavailable.
Troubleshooting
Metrics Not Being Collected
- Verify
enablePerformanceTracking: true in config
- Check browser supports Performance API
- Enable
debug: true to see console logs
Inaccurate Load Times
Ensure measurements are taken after the load event:
window.addEventListener("load", () => {
setTimeout(() => {
// Measure here
}, 0);
});
Performance tracking has minimal overhead, but if concerned:
- Sample performance data (track only 10% of sessions)
- Reduce custom measurements
- Increase batch sizes to reduce network overhead