Complete example demonstrating FlowTrace integration with React, TypeScript, and modern hooks.
- ✅ TypeScript Support - Full type safety with FlowTrace type definitions
- ✅ Decorator Pattern -
@Trace,@TraceClassdecorators for automatic tracing - ✅ React Hooks - Custom
useUsershook with typed state management - ✅ Service Layer - TypeScript service class with automatic tracing
- ✅ Modern React - Functional components, hooks, and TypeScript types
- ✅ Vite - Fast development with Hot Module Replacement
- ✅ Dashboard Integration - Analyze performance with FlowTrace Dashboard
cd examples/react-typescript
npm installnpm run dev:traceThis starts the development server with FlowTrace instrumentation enabled.
- Create, update, and delete users
- All service operations are automatically traced
- Logs are written to
flowtrace.jsonl
# In another terminal
node ../../flowtrace-dashboard/cli.js open flowtrace.jsonlOpen the dashboard URL in your browser to analyze performance metrics.
react-typescript/
├── src/
│ ├── components/
│ │ └── UserList.tsx # React component
│ ├── hooks/
│ │ └── useUsers.ts # Custom React hook
│ ├── services/
│ │ └── UserService.ts # Service with @TraceClass
│ ├── types/
│ │ └── User.ts # TypeScript interfaces
│ ├── App.tsx # Main application
│ ├── main.tsx # Entry point
│ └── index.css # Styles
├── package.json
├── tsconfig.json # TypeScript config with decorators
├── vite.config.ts # Vite configuration
└── README.md
import { TraceClass } from '../../../flowtrace-agent-js/src/decorators';
@TraceClass()
export class UserService {
// All methods automatically traced
async getAllUsers() { ... }
async createUser(data) { ... }
async updateUser(id, data) { ... }
}import { Trace } from '../../../flowtrace-agent-js/src/decorators';
export class AuthService {
@Trace()
async login(email: string, password: string) {
// Automatically traced
}
@Trace({ captureArgs: false })
async validateToken(token: string) {
// Traced without capturing arguments
}
}export function useUsers() {
const [users, setUsers] = useState<User[]>([]);
const fetchUsers = useCallback(async () => {
// Service call automatically traced
const data = await userService.getAllUsers();
setUsers(data);
}, []);
return { users, fetchUsers };
}Decorators require these compiler options:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Environment variables for tracing:
# Filter to only trace your code
FLOWTRACE_PACKAGE_PREFIX=src
# Log file output
FLOWTRACE_LOG_FILE=flowtrace.jsonl
# Disable console output (logs only to file)
FLOWTRACE_STDOUT=falseFlowTrace generates JSONL logs for each traced method:
{"timestamp":1635789012345,"event":"ENTER","thread":"main","class":"UserService","method":"getAllUsers","args":"[]"}
{"timestamp":1635789012567,"event":"EXIT","thread":"main","class":"UserService","method":"getAllUsers","args":"[]","result":"[{\"id\":1,...}]","durationMicros":222000,"durationMillis":222}The FlowTrace Dashboard provides:
- Performance Metrics - P50, P95, P99 percentiles
- Bottleneck Detection - Methods with high impact (frequency × duration)
- Error Tracking - Exception rates and error hotspots
- Time Distribution - Histogram of method durations
- Slowest Methods - Performance optimization targets
// Strongly typed interfaces
interface User {
id: number;
name: string;
email: string;
role: UserRole;
}
type UserRole = 'admin' | 'user' | 'guest';const [users, setUsers] = useState<User[]>([]);
const [selectedUser, setSelectedUser] = useState<User | null>(null);async getAllUsers(filters?: UserFilters): Promise<User[]> {
// TypeScript ensures type safety
const filtered = this.users.filter(u => u.role === filters?.role);
return filtered;
}npm run dev # Normal mode
npm run dev:trace # With FlowTrace instrumentationnpm run build
npm run previewnpx tsc --noEmit-
Declare Services at Module Level
// Good: Service declared before usage export class UserService { } export const userService = new UserService();
-
Use Decorators for Automatic Tracing
@TraceClass() // Easier than manual tracing export class DataService { }
-
Type Your Props and State
interface UserListProps { users: User[]; loading: boolean; }
-
Hoisting Dependencies
// Bad: Using before declaration const service = new UserService(); class UserService { }
-
Missing TypeScript Config
// Decorators won't work without: // "experimentalDecorators": true
Ensure tsconfig.json has:
{
"compilerOptions": {
"experimentalDecorators": true
}
}Check that FLOWTRACE_PACKAGE_PREFIX matches your source directory:
FLOWTRACE_PACKAGE_PREFIX=src # For src/ directoryInstall type definitions:
npm install --save-dev @types/react @types/react-dom @types/nodeMIT - See main FlowTrace LICENSE
Juan Pablo Diaz juanpablo516@gmail.com