+
+```
diff --git a/docs/src/content/en/docs/components/index.mdx b/docs/src/content/en/docs/components/index.mdx
new file mode 100644
index 0000000..d96617b
--- /dev/null
+++ b/docs/src/content/en/docs/components/index.mdx
@@ -0,0 +1,63 @@
+# Provider
+
+The `Provider` component initializes and supplies context to the application. It is one of the event components returned as the first element of the `createTracker` tuple.
+
+```tsx
+import { createTracker } from '@offlegacy/event-tracker'
+
+const [Track] = createTracker({...})
+
+function App() {
+ return (
+
+ {/* Application */}
+
+ )
+}
+```
+
+## Reference
+
+### Props
+
+| Prop | Type | Description | Required |
+| ---------------- | --------- | --------------------- | -------- |
+| `initialContext` | `Context` | Initial context value | Yes |
+
+---
+
+#### `initialContext` (Required)
+
+- **Type:** `Context`
+- **Description:** Defines the initial context value.
+
+## Examples
+
+### With Initial Context
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+type Context = {
+ userId: string;
+ trackingEnabled: boolean;
+};
+
+const [Track] = createTracker({});
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+`initialContext` defines the initial state accessible to all nested tracking components.
+This context can be used within `enabled`, `params`, and `SetContext`.
diff --git a/docs/src/content/en/docs/components/page-view.mdx b/docs/src/content/en/docs/components/page-view.mdx
new file mode 100644
index 0000000..d78fd8a
--- /dev/null
+++ b/docs/src/content/en/docs/components/page-view.mdx
@@ -0,0 +1,108 @@
+import { Callout } from "nextra/components";
+
+# PageView
+
+Tracks a page view event when the component mounts. It is one of the event components returned as the first element of the `createTracker` tuple.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({
+ pageView: {
+ onPageView: (params, context) => {
+ // Handle page view event
+ },
+ },
+});
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Prop | Type | Description | Required |
+| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------------- | -------- |
+| `enabled` | `boolean \| ((context: Context, params: EventParams) => boolean)` | Conditionally enable/disable event tracking (default: `true`) | - |
+| `debounce` | `DebounceConfig` | Debounce configuration to prevent rapid consecutive events | - |
+| `throttle` | `ThrottleConfig` | Throttle configuration to limit event frequency | - |
+| `schema` | `string` | Schema name for validating event parameters | O |
+
+
+ Note: `debounce` and `throttle` are mutually exclusive and cannot be used together. A type error will prevent invalid
+ usage.
+
+
+When using with schemas vs. without schemas, the `params` prop type differs.
+
+With schema:
+
+| Prop | Type | Description |
+| -------- | ---------------------------------------------------- | ----------------------- |
+| `params` | `SchemaParams \| (context: Context) => SchemaParams` | Schema-based parameters |
+
+Without schema:
+
+| Prop | Type | Description |
+| -------- | -------------------------------------------------- | ------------------- |
+| `params` | `EventParams \| (context: Context) => EventParams` | Standard parameters |
+
+---
+
+#### `params` (Required)
+
+With schema:
+
+- **Type:** `SchemaParams | (context: Context) => SchemaParams`
+- **Description:** Schema-based parameters
+
+Without schema:
+
+- **Type:** `EventParams | (context: Context) => EventParams`
+- **Description:** Event parameters
+
+#### `enabled`
+
+- **Type:** `boolean | ((context: Context, params: EventParams) => boolean)`
+- **Description:** Conditionally enable or disable event tracking (default: `true`)
+
+#### `debounce`
+
+- **Type:** `DebounceConfig`
+- **Description:** Configure debouncing to avoid multiple rapid event triggers.
+
+#### `throttle`
+
+- **Type:** `ThrottleConfig`
+- **Description:** Configure throttling to limit event frequency.
+
+#### `schema`
+
+When using schemas:
+
+- **Type:** `string`
+- **Description:** Schema name used to validate event parameters.
+
+## Examples
+
+### Conditional Event
+
+```tsx
+ context.trackingConsent === true}
+/>
+```
+
+### Debounced Page View
+
+```tsx
+
+```
diff --git a/docs/src/content/en/docs/components/set-context.mdx b/docs/src/content/en/docs/components/set-context.mdx
new file mode 100644
index 0000000..fc4cbf8
--- /dev/null
+++ b/docs/src/content/en/docs/components/set-context.mdx
@@ -0,0 +1,48 @@
+import { Callout } from "nextra/components";
+
+# SetContext
+
+Sets or updates the tracking context. It is one of the utility components returned as the first element of the `createTracker` tuple.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({ ... });
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Prop | Type | Description | Required |
+| --------- | ------------------------------------------------ | ----------------------------------------------------------------------- | -------- |
+| `context` | `Context \| ((prevContext: Context) => Context)` | New context value or a function to update based on the previous context | Yes |
+
+---
+
+#### `context` (Required)
+
+- **Type:** `Context | ((prevContext: Context) => Context)`
+- **Description:** You can either specify a new context directly or update it based on the previous context. Once rendered, this component updates the tracking context with the specified value.
+
+## Examples
+
+### Set Static Context
+
+```tsx
+
+```
+
+### Update Based on Previous Context
+
+```tsx
+ ({ ...prev, lastSeen: new Date() })} />
+```
diff --git a/docs/src/content/en/docs/create-tracker.mdx b/docs/src/content/en/docs/create-tracker.mdx
new file mode 100644
index 0000000..abb506c
--- /dev/null
+++ b/docs/src/content/en/docs/create-tracker.mdx
@@ -0,0 +1,128 @@
+# createTracker
+
+`createTracker` is a function that generates a tracker instance with custom configurations.
+Through its parameters, you define event tracking behavior, and the returned tuple provides access to the tracker instance.
+
+```tsx
+const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }, useTracker] = createTracker({
+ init,
+ send,
+ DOMEvents,
+ impression: {
+ onImpression,
+ options,
+ },
+ pageView: {
+ onPageView,
+ },
+ batch,
+ schemas,
+});
+```
+
+## Reference
+
+### Parameters
+
+`createTracker` accepts a single configuration object.
+
+| Property | Type | Description |
+| ------------ | ------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
+| `init` | `(initialContext: Context, setContext: SetContext) => void \| Promise` | Initialization function executed before any event occurs. Async supported. |
+| `send` | `(params: EventParams \| (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType` | Event dispatch function. Async supported. |
+| `DOMEvents` | [`DOMEvents`](https://developer.mozilla.org/docs/Web/API/Event) | Collection of React DOM event handlers (`onClick`, `onMouseEnter`, etc.) |
+| `impression` | `ImpressionOptions` | Impression event tracking configuration |
+| `pageView` | `PageViewOptions` | Page view tracking configuration |
+| `batch` | `BatchConfig` | Event batching configuration |
+| `schemas` | `SchemaConfig` | Event schema validation configuration |
+
+---
+
+#### `init`
+
+- **Type:** `(initialContext: Context, setContext: SetContext) => void | Promise`
+- **Description:** Function to initialize context before any event fires. Supports async.
+
+#### `send`
+
+- **Type:** `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
+- **Description:** Sends events to an external service. Supports async.
+
+#### `DOMEvents`
+
+- **Type:** `DOMEvents`
+- **Description:** Standard React DOM event handler object. Used in `` components.
+
+#### `impression`
+
+- **`impression.onImpression`**
+
+ - **Type:** `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
+ - **Description:** Callback executed when `` fires.
+
+- **`impression.options`**
+
+ - **Type:** `ImpressionOptions`
+ - **Properties:**
+
+ - `threshold`: Intersection ratio threshold (default: `0.2`)
+ - `freezeOnceVisible`: Whether to lock state after first impression (default: `true`)
+ - `initialIsIntersecting`: Initial intersection state (default: `false`)
+
+#### `pageView`
+
+- **`pageView.onPageView`**
+
+ - **Type:** `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
+ - **Description:** Callback executed when `` mounts.
+
+#### `batch`
+
+- **Type:** `BatchConfig`
+- **Properties:**
+
+ - `batch.enable`: Enable batching (default: `false`)
+ - `batch.interval`: Dispatch interval in ms (default: `3000`)
+ - `batch.thresholdSize`: Max batch size (default: `25`)
+ - `batch.onFlush`: Function to process batched events
+ - `batch.onError`: Optional error handler for batch failures
+
+#### `schemas`
+
+- **Type:** `SchemaConfig`
+- **Properties:**
+
+ - `schemas.schema`: [Zod](https://zod.dev/)-based schema definitions
+ - `schemas.onSchemaError`: Handler for schema validation errors
+ - `schemas.abortOnError`: Whether to abort events on validation error (default: `false`)
+
+### Returns
+
+`createTracker` returns a tuple with two elements:
+
+```tsx
+const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }, useTracker] = createTracker({...})
+```
+
+#### [Components](./components)
+
+The first element is an object containing event components:
+
+```tsx
+const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }] = createTracker(config);
+```
+
+- `Provider`
+- `DOMEvent`
+- `Click`
+- `Impression`
+- `PageView`
+- `SetContext`
+
+#### [Hook](./hook)
+
+```tsx
+const [, useTracker] = createTracker(config);
+```
+
+The second element is a custom React hook giving access to event tracking functions and context management inside components.
diff --git a/docs/src/content/en/docs/data-type-validation.mdx b/docs/src/content/en/docs/data-type-validation.mdx
new file mode 100644
index 0000000..7af3e43
--- /dev/null
+++ b/docs/src/content/en/docs/data-type-validation.mdx
@@ -0,0 +1,98 @@
+import { Callout, Steps } from "nextra/components";
+
+# Data Validation
+
+Event Tracker provides schema-based data type validation using [Zod](https://zod.dev/) to ensure the accuracy of event parameters.
+With this feature, events are validated against predefined structures before being collected, helping to ensure data reliability, prevent errors, and provide a foundation for structured analytics.
+
+## Usage
+
+Define Zod schemas and pass them to the `schemas` option in the `createTracker` configuration.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+import { z } from "zod";
+
+const schemas = {
+ page_view: z.object({
+ title: z.string(),
+ }),
+ click_button: z.object({
+ target: z.string(),
+ }),
+};
+
+const [Track] = createTracker<{}, {}, typeof schemas>({
+ schemas: {
+ schemas,
+ onSchemaError: (error) => {
+ console.error("Schema validation failed:", error);
+ },
+ abortOnError: true,
+ },
+});
+```
+
+## Reference
+
+| Option | Type | Description | Default |
+| --------------- | -------------------------------------------- | ----------------------------------------------------- | -------- |
+| `schemas` | `Record` | Mapping of event names to Zod schemas | Required |
+| `onSchemaError` | `(error: ZodError) => void \| Promise` | Function called when schema validation fails | Optional |
+| `abortOnError` | `boolean` | Whether to abort event processing on validation error | `false` |
+
+
+ When `abortOnError` is set to `true`, events that fail schema validation will not be tracked.
+
+
+## Examples
+
+
+
+### Define Zod Schemas
+
+```ts
+import { z } from "zod";
+
+const schemas = {
+ page_view: z.object({
+ title: z.string(),
+ }),
+ click_button: z.object({
+ target: z.string(),
+ }),
+};
+```
+
+### Register with `createTracker`
+
+```tsx
+const [Track] = createTracker<{}, {}, typeof schemas>({
+ schemas: {
+ schemas,
+ abortOnError: true,
+ onSchemaError: (error) => {
+ console.error("Schema error occurred", error);
+ },
+ },
+});
+```
+
+### Schema-Based Event Tracking
+
+```tsx
+
+
+```
+
+If schema validation passes, the event is sent to `send` or the respective handler.
+If it fails, `onSchemaError` is triggered, and if `abortOnError` is `true`, the event is discarded.
+
+
+
+## Notes
+
+- Zod schemas use [parse](https://zod.dev/?id=parse) for validation by default.
+- For better type inference, define schemas outside of the `createTracker` function and pass `typeof schemas` as the third type argument to `createTracker`.
+
+_Support for additional schema validation libraries is planned for the future._
diff --git a/docs/src/content/en/docs/hook.mdx b/docs/src/content/en/docs/hook.mdx
new file mode 100644
index 0000000..1d8b65b
--- /dev/null
+++ b/docs/src/content/en/docs/hook.mdx
@@ -0,0 +1,233 @@
+import { Callout } from "nextra/components";
+
+# Hook
+
+Inside a React component, you can configure the tracking context or imperatively trigger events. This hook is the second item returned from [`createTracker`](/docs/create-tracker).
+
+It is primarily used to manually trigger events after a component mounts, upon user input, or after asynchronous tasks complete.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track, useTracker] = createTracker({...});
+
+function MyComponent() {
+ const { setContext, getContext, track, trackWithSchema } = useTracker();
+
+ // Imperative event tracking
+}
+```
+
+## Reference
+
+### Returns
+
+| Property | Type | Description |
+| ----------------- | --------------------------------------------------------------- | --------------------------------------------------- |
+| `setContext` | `(context: Context \| (prev: Context) => Context) => void` | Sets or updates the tracking context |
+| `getContext` | `() => Context` | Returns the current tracking context |
+| `track` | `Record void>` | Collection of standard event tracking functions |
+| `trackWithSchema` | `Record void>` | Collection of schema-validated event tracking funcs |
+
+---
+
+#### `setContext`
+
+```tsx
+const { setContext } = useTracker();
+
+// Set a new context
+setContext({ userId: "user-123" });
+
+// Update context based on previous value
+setContext((prev) => ({
+ ...prev,
+ lastActive: new Date(),
+}));
+```
+
+- Sets or updates the current tracking context.
+- Useful for updating user information, session data, etc.
+
+#### `getContext`
+
+```tsx
+const { getContext } = useTracker();
+
+const currentContext = getContext();
+console.log("Current user:", currentContext.userId);
+```
+
+- Returns the current tracking context.
+- Useful for accessing the current tracking state.
+
+#### `track`
+
+```tsx
+const { track } = useTracker();
+
+// Simple click event tracking
+track.onClick({ buttonId: "submit" });
+
+// Conditional tracking
+track.onClick(
+ { buttonId: "premium" },
+ {
+ enabled: (context) => context.user?.isPremium,
+ },
+);
+
+// Tracking with debouncing
+track.onClick(
+ { buttonId: "search" },
+ {
+ debounce: { delay: 300, leading: false, trailing: true },
+ },
+);
+
+// Tracking with throttling
+track.onClick(
+ { buttonId: "rapid-action" },
+ {
+ throttle: { delay: 1000, leading: true, trailing: false },
+ },
+);
+
+// Impression event tracking
+track.onImpression({ elementId: "hero" });
+```
+
+- An object containing all configured event tracking functions.
+- Keys match event names defined in the tracker configuration.
+- Supports optional `TrackingOptions` for advanced control.
+
+#### `trackWithSchema`
+
+```tsx
+const { trackWithSchema } = useTracker();
+
+// Track a click event with schema validation
+trackWithSchema.onClick({ schema: "click", params: { buttonId: "submit" } });
+
+// Conditional tracking with schema
+trackWithSchema.onClick(
+ {
+ schema: "premium_click",
+ params: { buttonId: "premium", userId: "123" },
+ },
+ {
+ enabled: (context, params) => context.user?.id === params.userId,
+ },
+);
+
+// Tracking with schema and throttling
+trackWithSchema.onImpression(
+ {
+ schema: "impression",
+ params: { elementId: "hero", userId: "123" },
+ },
+ {
+ throttle: { delay: 2000, leading: true, trailing: false },
+ },
+);
+```
+
+- An object containing all schema-validated event tracking functions.
+- Keys match event names defined in the tracker configuration.
+- Supports optional `TrackingOptions` for advanced control.
+
+## TrackingOptions
+
+Both `track` and `trackWithSchema` accept the following optional configuration:
+
+| Option | Type | Description |
+| ---------- | ------------------------------------------- | --------------------------------------------------- |
+| `enabled` | `boolean \| ((context, params) => boolean)` | Enables/disables event tracking conditionally |
+| `debounce` | `DebounceConfig` | Limits consecutive events (triggers last call only) |
+| `throttle` | `ThrottleConfig` | Prevents repeated calls in a short time window |
+
+
+ Note: `debounce` and `throttle` are mutually exclusive and cannot be used together. A type error will prevent invalid
+ usage.
+
+
+#### `DebounceConfig`
+
+```ts
+interface DebounceConfig {
+ delay: number;
+ leading?: boolean; // Default: false
+ trailing?: boolean; // Default: true
+}
+```
+
+#### `ThrottleConfig`
+
+```ts
+interface ThrottleConfig {
+ delay: number;
+ leading?: boolean; // Default: true
+ trailing?: boolean; // Default: false
+}
+```
+
+## Best Practices
+
+### Context Management
+
+- Use `setContext` to update global state that affects multiple events.
+- Consider the functional form of `setContext` for updates based on previous state.
+
+### Event Tracking
+
+- Use the event functions from `track` or `trackWithSchema` wherever possible.
+
+### Performance Optimization
+
+- Avoid calling event tracking functions during rendering.
+- Use [Batching](/docs/batching) to improve performance.
+- Use [Data Validation](/docs/data-type-validation) to ensure data safety.
+
+## Examples
+
+### Basic
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track, useTracker] = createTracker({
+ onClick: (params) => {
+ // Send event to analytics service
+ analytics.track(params);
+ },
+ pageView: {
+ onPageView: (params) => {
+ analytics.pageView(params);
+ },
+ },
+});
+
+function UserProfile({ userId }) {
+ const { setContext, track, trackWithSchema } = useTracker();
+
+ useEffect(() => {
+ // Update context when userId changes
+ setContext({ userId });
+
+ // Track page view event
+ track.onPageView({ page: "profile" });
+ }, [userId]);
+
+ const handleSettingsClick = () => {
+ // Track user settings event
+ trackWithSchema.onClick({ schema: "settings", params: { userId } });
+ };
+
+ return (
+
+
User Profile
+
+
+ );
+}
+```
diff --git a/docs/src/content/en/docs/installation.mdx b/docs/src/content/en/docs/installation.mdx
new file mode 100644
index 0000000..d88a53e
--- /dev/null
+++ b/docs/src/content/en/docs/installation.mdx
@@ -0,0 +1,11 @@
+# Installation
+
+Event Tracker is a library designed to make implementing event tracking in React applications simple and efficient. It supports `React@^16.8.0` and above.
+
+To install the latest stable version, run the following command:
+
+
+
+```shell npm2yarn
+npm install @offlegacy/event-tracker
+```
diff --git a/docs/src/content/en/docs/introduction.mdx b/docs/src/content/en/docs/introduction.mdx
new file mode 100644
index 0000000..a1af609
--- /dev/null
+++ b/docs/src/content/en/docs/introduction.mdx
@@ -0,0 +1,83 @@
+# Introduction
+
+Welcome to the Event Tracker documentation.
+
+## What is Event Tracker?
+
+Event Tracker is a declarative React library that simplifies the process of implementing complex event tracking, allowing developers to focus more on business logic. It is designed to make event tracking easy and efficient for applications of any scale.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+// Create a tracker instance
+const [Track, useTracker] = createTracker({
+ DOMEvents: {
+ onClick: (params, context) => {
+ log("Click event:", params, context);
+ },
+ },
+});
+
+// Usage in the app
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+### Key Features
+
+Event Tracker provides a wide range of features focused on both developer experience and application performance.
+
+| Feature | Description |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Declarative API | Easily declare tracking as components without additional setup or complex code. |
+| Analytics Tool Agnostic | Integrate with any tool such as [Google Analytics](https://analytics.google.com/) or [Amplitude](https://amplitude.com/) without modifying existing infrastructure. |
+| Clear Separation of Concerns | Keep tracking logic completely separate from business code, improving readability, testability, and maintainability. |
+| Optimized Performance | Built-in strategies like batching, debouncing, and throttling minimize network requests, enabling stable tracking without performance degradation. |
+| Guaranteed Execution Order | Ensures events are processed in the intended order even in asynchronous scenarios, enabling accurate tracking in complex user flows. |
+| Data Validation | Built-in static schema validation with [Zod](https://zod.dev/) prevents build-time errors and ensures the reliability of collected event data. |
+
+## Core Concepts
+
+To use Event Tracker effectively, there are several key concepts to understand.
+
+### Instance (`createTracker`)
+
+This is the fundamental starting point of the library. Using the `createTracker` function, you create a tracker instance (a collection of `Track` components and the `useTracker` hook). Here, you define event tracking by configuring DOM event handlers, impression handlers, and schemas.
+
+You can create multiple tracker instances for different purposes (for example, one for Google Analytics and another for Amplitude).
+
+### Provider (`Track.Provider`)
+
+Implemented based on React’s Context API. Wrap the top level of your application or a specific component tree with `Track.Provider` to supply common data (context) needed for tracking to child components. For example, passing `userId` or `pageName` as context allows these values to be used during event tracking.
+
+### Event Components (`Track.Click`, `Track.PageView`, etc.)
+
+These are special components that enable declarative event tracking. They are provided as the first element in the array returned by `createTracker`.
+
+- `Track.Click`: Tracks when a click event occurs on child elements.
+- `Track.Impression`: Tracks when child elements are displayed on screen.
+- `Track.PageView`: Tracks a page view event when the component mounts.
+
+You can use the provided components or create custom ones to handle various user interactions and lifecycle events. Each component accepts `context` and `params` props to pass specific data relevant to the event.
+
+### Custom Hook
+
+Use when you need more complex or conditional event tracking that is not directly tied to component lifecycle or DOM events. The hook allows you to access context from `Track.Provider` and execute defined tracking logic imperatively.
+
+## Next Steps
+
+These core concepts work together to create a powerful and flexible event tracking environment with Event Tracker. For more detailed usage and in-depth information on each feature, see the following documentation:
+
+- [Why Event Tracker?](/docs/why-event-tracker): Learn the necessity and main features of Event Tracker.
+- [`createTracker`](/docs/create-tracker): Learn how to create and configure a tracker instance.
+- [Components](/docs/components): Explore all available tracking components with usage examples.
+- [Hook](/docs/hook): Learn how to implement custom tracking with the hook.
+- [Batching](/docs/batching): Optimize performance through event batching strategies.
+- [Data Validation](/docs/data-type-validation): Ensure data integrity with Zod schema validation.
diff --git a/docs/src/content/en/docs/why-event-tracker.mdx b/docs/src/content/en/docs/why-event-tracker.mdx
new file mode 100644
index 0000000..101790f
--- /dev/null
+++ b/docs/src/content/en/docs/why-event-tracker.mdx
@@ -0,0 +1,196 @@
+import { Steps } from "nextra/components";
+
+# Why Event Tracker?
+
+Modern web applications must continuously analyze user behavior to improve service quality. However, traditional event tracking approaches come with several challenges.
+
+## Why You Need Event Tracker
+
+The following example highlights common issues with conventional event tracking.
+
+```tsx {8,15, 24-31}
+function Page() {
+ const { user, userId } = useUser(); // Fetch user info and ID.
+
+ return (
+
+
User: {user.name}
+ {/* Passing userId to Counter solely for event tracking */}
+
+
+ );
+}
+```
+
+
+
+### The Pain of Prop Drilling
+
+To pass tracking-related data down to nested components, you often end up drilling props through multiple layers. This reduces code readability and complicates maintenance.
+
+### Tight Coupling of Logic
+
+Mixing business logic with tracking logic increases code complexity and makes independent testing and modification harder.
+
+### Increased Boilerplate
+
+Repetitive tracking code reduces developer productivity.
+
+
+
+## A New Paradigm with Event Tracker
+
+Event Tracker introduces a new paradigm for event tracking. Its declarative approach simplifies the inherent complexity of traditional tracking and makes it accessible to all developers.
+
+
+
+### Declarative Event Tracking
+
+```tsx {7, 10, 12, 32, 34}
+function Page() {
+ const { user, userId } = useUser();
+
+ // Provide tracking context (userId) to child components via Track.Provider.
+ // No more prop drilling required.
+ return (
+
+
+ {/*
+ Track.Click wraps the button and tracks the click event
+ with the defined parameters. userId from context is automatically
+ included in the tracking data.
+ */}
+
+
+
+
+ );
+}
+```
+
+With Event Tracker, declarative event tracking improves code readability and reduces complexity. This helps developers focus on _what_ to track rather than _how_ to track.
+The `handleIncrement` function now handles only count logic, while `` manages tracking.
+**This declarative approach shifts the developer’s focus from implementation details to defining the intent of tracking.**
+How tracking is handled is defined outside the React app.
+
+### Improved Tracking Cohesion
+
+```tsx {4-10, 14-20}
+const [Track, useTracker] = createTracker({
+ // Callback for DOM events
+ DOMEvents: {
+ onClick: (params, context) => {
+ // Call actual tracking tools (Google Analytics, Amplitude, etc.)
+ logEvent("click_event", {
+ ...params, // { value: ..., type: "count" }
+ userId: context.userId, // Provided by the Provider
+ });
+ },
+ // You can also define onMouseOver, onFocus, etc.
+ },
+ // Callback for Impression events
+ onImpression: (params, context) => {
+ logEvent("impression_event", {
+ ...params,
+ userId: context.userId,
+ pagePath: window.location.pathname,
+ });
+ },
+});
+```
+
+Now, the code defining _how to track_ is separated from business logic. Since it's located outside the application, you can modify tracking logic without touching business code.
+
+### Data Validation
+
+```tsx {13-20, 24-33}
+import { z } from "zod";
+import { createTracker } from "@offlegacy/event-tracker";
+
+interface Context {
+ /* ... */
+}
+
+interface Params {
+ /* ... */
+}
+
+// Define schemas
+const schemas = {
+ page_view: z.object({
+ title: z.string(),
+ }),
+ click_button: z.object({
+ target: z.string(),
+ }),
+};
+
+// Configure tracker
+const [Track] = createTracker({
+ schema: {
+ schemas: {
+ page_view,
+ click_button,
+ },
+ onSchemaError: (error) => {
+ console.error("Schema validation error:", error);
+ },
+ abortOnError: true,
+ },
+});
+
+// Using schemas
+;
+;
+```
+
+Event Tracker integrates with [Zod](https://zod.dev/) to provide robust schema-based data type validation. This prevents data errors during development and enhances the reliability of tracking data.
+
+
diff --git a/docs/src/content/en/docs/with-google-analytics-example.mdx b/docs/src/content/en/docs/with-google-analytics-example.mdx
new file mode 100644
index 0000000..4b449a6
--- /dev/null
+++ b/docs/src/content/en/docs/with-google-analytics-example.mdx
@@ -0,0 +1,115 @@
+import { Steps } from "nextra/components";
+
+# Integrating with Google Analytics
+
+This guide walks you through integrating GA4 (Google Analytics 4) to track user behavior step by step.
+
+
+
+## Set Up GA4 Script
+
+Add the GA4 script to the `` of your `index.html` to enable `gtag`.
+
+```html
+
+
+
+
+
+```
+
+## Define `sendGA4` Function
+
+Create a wrapper function to safely call `gtag` with validation and warnings.
+
+```ts
+export function sendGA4(eventName: string, eventParams: Record = {}): void {
+ if (typeof window === "undefined") return;
+ if (typeof window.gtag !== "function") {
+ console.warn("[GA4] gtag function is not loaded.");
+ return;
+ }
+ window.gtag("event", eventName, eventParams);
+}
+```
+
+## Define Tracking Events
+
+Configure `createTracker` with GA4 event sending logic and set up DOM, impression, and page view events.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+import { sendGA4 } from "./sendGA4";
+
+interface GA4Context {
+ userId: string;
+}
+
+interface GA4EventParams {
+ eventName: string;
+}
+
+export const [Track, useTracker] = createTracker({
+ DOMEvents: {
+ onClick: (params, ctx) => sendGA4(params.eventName, { ...params, user_id: ctx.userId }),
+ },
+ impression: {
+ onImpression: (params, ctx) => sendGA4("impression", { ...params, user_id: ctx.userId }),
+ options: { threshold: 0.5, freezeOnceVisible: true },
+ },
+});
+```
+
+## Use in a Blog Page
+
+Wrap your app in `Track.Provider` and use ``, ``, and `` components to declaratively record events.
+
+```tsx
+import { Track } from "./event-tracker";
+
+function App() {
+ return (
+
+
+
+ );
+}
+
+interface PostProps {
+ id: number;
+ title: string;
+ slug: string;
+ content: string;
+}
+
+function Post({ post }: PostProps) {
+ return (
+
+
{post.title}
+
+
+
{post.content}
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
+```
+
+
diff --git a/docs/src/content/en/docs/with-zod-example.mdx b/docs/src/content/en/docs/with-zod-example.mdx
new file mode 100644
index 0000000..c1aec6e
--- /dev/null
+++ b/docs/src/content/en/docs/with-zod-example.mdx
@@ -0,0 +1,72 @@
+import { Steps } from "nextra/components";
+
+# Using with Zod
+
+Learn how to implement powerful data type validation by integrating [Zod](https://zod.dev/).
+Schema-based validation with Zod helps prevent errors before runtime and ensures data reliability.
+
+
+
+## Define Schemas
+
+Declare event-specific fields and types using Zod objects.
+
+```tsx {4-5}
+import { z } from "zod";
+
+export const schemas = {
+ page_view: z.object({ title: z.string() }),
+ click_button: z.object({ target: z.string() }),
+};
+```
+
+## Define Tracking Events
+
+Connect the schemas to `createTracker` to automatically validate event parameters.
+
+```tsx {5-9}
+import { createTracker } from "@offlegacy/event-tracker";
+import { schemas } from "./schemas";
+
+export const [Track, useTracker] = createTracker<{}, {}, typeof schemas>({
+ schemas: {
+ schemas,
+ onSchemaError: (error) => console.error("Schema validation failed:", error),
+ abortOnError: true,
+ },
+});
+```
+
+## Use Validated Events
+
+Send type-safe events via declarative components and the `track` function.
+
+```tsx {11, 17-19}
+import { Track } from "./event-tracker";
+
+function HomePage() {
+ return (
+
+
Homepage
+
+ {/* ✅ Valid with Zod schema, no type error */}
+
+
+ {/* 🚨 Invalid with Zod schema, type error */}
+ {/* */}
+
+ {/* ✅ Valid with Zod schema, no type error */}
+
+
+
+
+ {/* 🚨 Invalid with Zod schema, type error */}
+ {/*
+
+ */}
+
+ );
+}
+```
+
+
diff --git a/docs/src/content/en/hook.mdx b/docs/src/content/en/hook.mdx
deleted file mode 100644
index 0c8c4e2..0000000
--- a/docs/src/content/en/hook.mdx
+++ /dev/null
@@ -1,223 +0,0 @@
-# hook
-
-A custom React hook returned as the second array item from [`createTracker`](/docs/create-tracker).
-It provides access to tracking functionality and context management within your components.
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-const [Track, useTracker] = createTracker({...})
-
-function MyComponent() {
- const { setContext, getContext, track, trackWithSchema } = useTracker();
-
- return (
- // Your component content
- );
-}
-```
-
-### Return Value
-
-The hook returns an object with the following properties:
-
-#### setContext
-
-- Type: `(context: Context) => void`
-- Sets or updates the current tracking context
-- Can be used to update user information, session data, etc.
-
-```tsx
-const { setContext } = useTracker();
-
-// Set new context
-setContext({ userId: "user-123" });
-
-// Update context based on previous value
-setContext((prev) => ({
- ...prev,
- lastActive: new Date(),
-}));
-```
-
-#### getContext
-
-- Type: `() => Context`
-- Returns the current tracking context
-- Useful for accessing current tracking state
-
-```tsx
-const { getContext } = useTracker();
-
-const currentContext = getContext();
-console.log("Current user:", currentContext.userId);
-```
-
-#### track
-
-- Type: `Record void>`
-- Object containing all configured event tracking functions
-- Keys match the event names defined in your tracker configuration
-- Accepts optional `TrackingOptions` for advanced control
-
-```tsx
-const { track } = useTracker();
-
-// Track a simple click event
-track.onClick({ buttonId: "submit" });
-
-// Track with conditional logic
-track.onClick(
- { buttonId: "premium" },
- {
- enabled: (context) => context.user?.isPremium,
- },
-);
-
-// Track with debouncing
-track.onClick(
- { buttonId: "search" },
- {
- debounce: { delay: 300, leading: false, trailing: true },
- },
-);
-
-// Track with throttling
-track.onClick(
- { buttonId: "rapid-action" },
- {
- throttle: { delay: 1000, leading: true, trailing: false },
- },
-);
-
-// Track an impression
-track.onImpression({ elementId: "hero" });
-```
-
-#### trackWithSchema
-
-- Type: `Record void>`
-- Object containing all configured event tracking functions with schema validation
-- Keys match the event names defined in your tracker configuration
-- Accepts optional `TrackingOptions` for advanced control
-
-```tsx
-const { trackWithSchema } = useTracker();
-
-// Track a click event with schema
-trackWithSchema.onClick({ schema: "click", params: { buttonId: "submit" } });
-
-// Track with conditional logic and schema
-trackWithSchema.onClick(
- {
- schema: "premium_click",
- params: { buttonId: "premium", userId: "123" },
- },
- {
- enabled: (context, params) => context.user?.id === params.userId,
- },
-);
-
-// Track with throttling and schema
-trackWithSchema.onImpression(
- {
- schema: "impression",
- params: { elementId: "hero", userId: "123" },
- },
- {
- throttle: { delay: 2000, leading: true, trailing: false },
- },
-);
-```
-
-### TrackingOptions
-
-Both `track` and `trackWithSchema` methods accept an optional second parameter with the following options:
-
-- `enabled?: boolean | ((context: Context, params: EventParams) => boolean)` - Conditionally enable/disable event tracking
-- `debounce?: DebounceConfig` - Debounce configuration to prevent rapid successive events
-- `throttle?: ThrottleConfig` - Throttle configuration to limit event frequency
-
-**Note:** `debounce` and `throttle` are mutually exclusive and cannot be used together.
-
-#### DebounceConfig
-
-```tsx
-interface DebounceConfig {
- delay: number; // Delay in milliseconds
- leading?: boolean; // Execute on leading edge (default: false)
- trailing?: boolean; // Execute on trailing edge (default: true)
-}
-```
-
-#### ThrottleConfig
-
-```tsx
-interface ThrottleConfig {
- delay: number; // Delay in milliseconds
- leading?: boolean; // Execute on leading edge (default: true)
- trailing?: boolean; // Execute on trailing edge (default: false)
-}
-```
-
-### Example Usage
-
-Here's a complete example showing how to use the custom hook:
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-const [Track, useTracker] = createTracker({
- onClick: (params) => {
- // Send event to analytics service
- analytics.track(params);
- },
- pageView: {
- onPageView: (params) => {
- // Send event to analytics service
- analytics.pageView(params);
- },
- },
-});
-
-function UserProfile({ userId }) {
- const { setContext, track, trackWithSchema } = useTracker();
-
- useEffect(() => {
- // Update context when user ID changes
- setContext({ userId });
-
- // Track page view
- track.onPageView({ page: "profile" });
- }, [userId]);
-
- const handleSettingsClick = () => {
- // Track custom event
- trackWithSchema.onClick({ schema: "settings", params: { userId } });
- };
-
- return (
-
-
User Profile
-
-
- );
-}
-```
-
-### Best Practices
-
-1. **Context Updates**
-
- - Use `setContext` for global state that affects multiple events
- - Consider using the function form of `setContext` for updates based on previous state
-
-2. **Event Tracking**
-
- - Use the specific event functions from `track` or `trackWithSchema` when possible
-
-3. **Performance**
- - Avoid calling tracking functions in render
- - Use callbacks or effects for tracking
- - Consider using [batching](/docs/batching) for better performance
- - Consider using [data type validation](/docs/data-type-validation) for data type safety
diff --git a/docs/src/content/en/index.mdx b/docs/src/content/en/index.mdx
index 2a87bb1..ee84f82 100644
--- a/docs/src/content/en/index.mdx
+++ b/docs/src/content/en/index.mdx
@@ -1,202 +1,42 @@
-# Introduction
-
-## Motivation
-
-Event tracking is a complex task that requires a lot of boilerplate code and complexity.
-Take a look at this example.
-
-```tsx {14,15, 23-30}
-// Traditional event tracking
-
-const Page = () => {
- const { user, userId } = useUser();
-
- return (
-
- );
-};
-```
-
-The two main inconveniences caused by event tracking in the code are:
-
-1. **Prop Drilling**: The `userId` is passed as a prop to the `` component from the `` component. If the `` component is nested deeper within the component tree, prop drilling can become more severe, reducing the readability and maintainability of the code.
-2. **Coupling of Event Tracking Logic and Business Logic**: The `handleIncrement` function contains both the logic for incrementing the count and tracking the event. Separating the event tracking logic can make the code cleaner and easier to maintain.
-
-## The New Paradigm
-
-`event-tracker` introduces a new paradigm for event tracking.
-The declarative nature of this paradigm simplifies
-the complexity traditionally associated with event tracking, making it accessible to developers of all skill levels.
-
-### Declarative event tracking
-
-```tsx {5, 10, 24, 26}
-const Page = () => {
- const { user, userId } = useUser();
-
- return (
-
-
- );
-};
-```
-
-Using `event-tracker` allows for declarative event tracking, which improves code readability and reduces complexity. This helps developers understand and use event tracking more easily.
-Your `handleIncrement` function is now only responsible for incrementing the count, and the event tracking is handled by the `` component.
-**This declarative approach makes the developer focus on _'what to track'_ and not _'how to track'._**
-How to track should be defined outside of the React app.
-
-### Improve code cohesion outside your application.
-
-```tsx
-const [Track] = createTracker({
- DOMEvents: {
- onClick: (params, context) => {
- log({
- event: "click",
- params: {
- ...params,
- userId: context.userId,
- },
- });
+---
+title: Event Tracker | Comprehensive solution for event tracking in React applications
+---
+
+import HomePage from "@/components/home-page";
+
+ {
- log({
- event: "impression",
- params: {
- ...params,
- userId: context.userId,
- },
- });
- },
-});
-```
-
-Your instructions for **'how to track'** is now separated from your business logic.
-It's located outside your application, so you can change your event tracking provider without having to change your application code.
-
-### Data Type Validation
-
-`event-tracker` provides built-in schema validation using [Zod](https://zod.dev/), a TypeScript-first schema validation library.
-
-```tsx
-import { z } from "zod";
-import { createTracker } from "@offlegacy/event-tracker";
-
-interface Context {
- // ...
-}
-
-interface Params {
- // ...
-}
-
-// Define Schemas
-const schemas = {
- page_view: z.object({
- title: z.string(),
- }),
- click_button: z.object({
- target: z.string(),
- }),
-};
-
-// Configure Tracker
-const [Track] = createTracker({
- // other configurations...
-
- schema: {
- schemas: {
- page_view,
- click_button,
+ {
+ title: "Analytics Tool Independence",
+ description:
+ "Easily integrates with tools like Google Analytics, Amplitude, or Segment—without forcing you to switch or couple to a specific vendor.",
},
- onSchemaError: (error) => {
- console.error("Schema validation error:", error);
+ {
+ title: "Clear Separation of Concerns",
+ description:
+ "Keeps tracking logic out of your business logic, resulting in cleaner code that’s easier to test, maintain, and evolve.",
},
- abortOnError: true,
- },
-});
-
-// Use the schemas
-;
-;
-```
-
-## Key Features
-
-- 🎯 **Type-safe APIs**: Declarative event tracking with complete type safety
-- 🛡️ **Data Type Validation**: Ensures data type safety and consistency using schemas
-- ⚡️ **Optimized Performance**: Enhanced performance through event batching
-- 🔄 **Guaranteed Order**: Guaranteed execution order for async operations
-- 🔌 **Analytics Agnostic**: Works with any analytics provider of your choice
-- 🧩 **Clean Separation**: Keeps tracking logic separate from business logic
-- 📦 **Lightweight**: Minimal bundle size impact on your application
-
-## Basic Concepts
-
-`event-tracker` is built around a few core concepts:
-
-1. **Tracker Creation**: Use `createTracker` to create a tracker instance with your desired event tracking instructions.
-2. **Provider**: Wrap your app with `Track.Provider` to provide context.
-3. **Event Components**: Use components like `Track.Click` or `Track.Impression` to track events.
-4. **Hooks**: Use the `useTracker` hook to access tracking functionality in your components imperatively.
-
-Check out the other sections for detailed documentation on each feature:
-
-- [createTracker](/docs/create-tracker) - Detailed API documentation on `createTracker`
-- [components](/docs/components) - Available tracking components
-- [hook](/docs/hook) - Track using the hook
-- [Batching](/docs/batching) - Optimizing performance with event batching
-- [Data Type Validation](/docs/data-type-validation) - Ensuring data type safety and consistency using schemas
+ {
+ title: "Optimized Performance",
+ description:
+ "Built-in strategies like batching, debouncing, and throttling minimize network overhead, enabling efficient and reliable tracking.",
+ },
+ {
+ title: "Guaranteed Execution Order",
+ description:
+ "Ensures that events are processed in the intended order, even under asynchronous conditions—crucial for accurate tracking in complex flows.",
+ },
+ {
+ title: "Powerful Data Validation",
+ description:
+ "Schema-based validation with Zod catches issues before runtime and guarantees the integrity of your event data.",
+ },
+ ]}
+/>
diff --git a/docs/src/content/en/installation.mdx b/docs/src/content/en/installation.mdx
deleted file mode 100644
index d2c9a98..0000000
--- a/docs/src/content/en/installation.mdx
+++ /dev/null
@@ -1,19 +0,0 @@
-# Installation
-
-Using npm:
-
-```bash
-npm install @offlegacy/event-tracker
-```
-
-Using yarn:
-
-```bash
-yarn add @offlegacy/event-tracker
-```
-
-Using pnpm:
-
-```bash
-pnpm add @offlegacy/event-tracker
-```
diff --git a/docs/src/content/en/quick-start.mdx b/docs/src/content/en/quick-start.mdx
deleted file mode 100644
index 0a5728b..0000000
--- a/docs/src/content/en/quick-start.mdx
+++ /dev/null
@@ -1,27 +0,0 @@
-# Quick Start
-
-Here's a simple example of how to use event-tracker:
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-// Create a tracker instance
-const [Track, useTracker] = createTracker({
- DOMEvents: {
- onClick: (params, context) => {
- log("Click event:", params, context);
- },
- },
-});
-
-// Use in your app
-function App() {
- return (
-
-
-
-
-
- );
-}
-```
diff --git a/docs/src/content/ko/_meta.ts b/docs/src/content/ko/_meta.ts
deleted file mode 100644
index 2a81597..0000000
--- a/docs/src/content/ko/_meta.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { MetaRecord } from "nextra";
-
-const meta: MetaRecord = {
- "getting-started-separator": {
- type: "separator",
- title: "시작하기",
- },
- index: {
- title: "소개",
- theme: {
- toc: true,
- layout: "default",
- },
- },
- installation: {
- title: "설치",
- theme: {
- toc: true,
- layout: "default",
- },
- },
- "quick-start": {
- title: "가이드",
- theme: {
- toc: true,
- layout: "default",
- },
- },
- "api-separator": {
- title: "API",
- type: "separator",
- },
- "create-tracker": {
- title: "createTracker",
- theme: {
- toc: true,
- layout: "default",
- },
- },
- components: {
- title: "컴포넌트",
- theme: {
- toc: true,
- layout: "default",
- },
- },
- hook: {
- title: "hook",
- theme: {
- toc: true,
- layout: "default",
- },
- },
- "advanced-separator": {
- title: "고급",
- type: "separator",
- },
- batching: {
- title: "배칭",
- theme: {
- toc: true,
- layout: "default",
- },
- },
-};
-
-export default meta;
diff --git a/docs/src/content/ko/_meta.tsx b/docs/src/content/ko/_meta.tsx
new file mode 100644
index 0000000..6fef8c5
--- /dev/null
+++ b/docs/src/content/ko/_meta.tsx
@@ -0,0 +1,16 @@
+import type { MetaRecord } from "nextra";
+
+export default {
+ index: {
+ type: "page",
+ display: "hidden",
+ theme: {
+ layout: "full",
+ toc: false,
+ },
+ },
+ docs: {
+ type: "page",
+ title: "문서보기",
+ },
+} satisfies MetaRecord;
diff --git a/docs/src/content/ko/batching.mdx b/docs/src/content/ko/batching.mdx
deleted file mode 100644
index e003e7f..0000000
--- a/docs/src/content/ko/batching.mdx
+++ /dev/null
@@ -1,128 +0,0 @@
-# 배칭
-
-## 개요
-
-이벤트 배칭은 여러 이벤트를 묶어서 애널리틱스 서비스에 보내기 전에 진행하는 성능 최적화 기술입니다. 이는 다음과 같은 경우에 특히 유용합니다:
-
-- 내부 배칭 기능이 있는 애널리틱스 서비스(Amplitude 또는 Google Analytics)를 사용하지 않는 경우
-- 네트워크 요청 수를 줄이고 싶은 경우
-- 성능을 최적화하고 싶은 경우
-
-## 설정
-
-트래커 설정에서 배칭을 활성화합니다:
-
-```tsx
-const [Track, useTracker] = createTracker({
- // ... other config
- batch: {
- enable: true,
- interval: 2000,
- thresholdSize: 100,
- onFlush: (batch, isBrowserClosing) => {
- if (isBrowserClosing) {
- // 브라우저가 닫힐 때 신뢰할 수 있는 전송을 위해 sendBeacon 사용
- navigator.sendBeacon("/analytics/collect/batch", JSON.stringify(batch));
- return;
- }
-
- // 일반 배칭 처리
- fetch("/analytics/collect/batch", {
- method: "POST",
- body: JSON.stringify(batch),
- });
- },
- },
-});
-```
-
-### 옵션
-
-- `enable: boolean` (기본값: `false`)
- - 배칭 활성화/비활성화
-- `interval: number` (기본값: `3000`)
- - 배칭 처리 간격 (ms)
-- `thresholdSize: number` (기본값: `25`)
- - 배칭 처리 전 최대 이벤트 수
-- `onFlush: (batch: Batch[], isBrowserClosing: boolean) => void | Promise`
- - 배칭 활성화 시 필요
- - 배칭 처리 함수
- - `isBrowserClosing` 브라우저 닫힘 시 배칭 처리 여부
-- `onError: (error: Error) => void | Promise`
- - 배칭 처리 실패 시 오류 처리 함수
-
-## 작동 방식
-
-1. 이벤트는 메모리에 수집됩니다
-2. 다음 중 하나가 발생할 때 배칭이 처리됩니다:
- - 구성된 간격이 도달합니다
- - 배칭 크기가 임계치에 도달합니다
- - 브라우저가 닫힐 때
-
-### 예시
-
-```tsx
-const [Track, useTracker] = createTracker({
- DOMEvents: {
- onClick: (clickParams, context) => {
- // 반환 값이 배칭됩니다
- return {
- ...clickParams,
- ...context,
- event_type: "click",
- timestamp: new Date().getTime(),
- };
- },
- },
- batch: {
- enable: true,
- interval: 2000,
- thresholdSize: 100,
- onFlush: (batch, isBrowserClosing) => {
- // Process the batch
- },
- },
-});
-
-function App() {
- return (
-
-
-
-
-
- );
-}
-```
-
-버튼을 여러 번 클릭했을 때:
-
-1. 각 클릭은 `onClick` 핸들러를 실행합니다
-2. 각 핸들러의 반환 값은 배치 큐에 추가됩니다
-3. 2초(또는 임계치에 도달할 때)가 지나면 `onFlush`가 모든 수집된 이벤트와 함께 호출됩니다
-
-## 브라우저 닫힘 시 동작
-
-브라우저가 닫힐 때, [`navigator.sendBeacon`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)을 사용하여 이벤트 전송을 보장합니다:
-
-```tsx
-onFlush: (batch, isBrowserClosing) => {
- if (isBrowserClosing) {
- navigator.sendBeacon("/analytics/collect/batch", JSON.stringify(batch));
- return;
- }
-
- // 일반 배칭 처리
- fetch("/analytics/collect/batch", {
- method: "POST",
- body: JSON.stringify(batch),
- });
-};
-```
-
-## 유의 사항
-
-1. 이벤트 핸들러의 **반환 값**만 배칭되며, 핸들러 자체는 배칭되지 않습니다
-2. 배칭된 이벤트는 원래 매개변수와 컨텍스트를 유지합니다
-3. 이벤트는 순서대로 처리되며, 사용자 작업의 순서를 유지합니다
-4. 브라우저 닫힘 시 이벤트 전송을 보장하기 위해 [`navigator.sendBeacon`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)을 사용합니다
diff --git a/docs/src/content/ko/components/click.mdx b/docs/src/content/ko/components/click.mdx
deleted file mode 100644
index 96469f7..0000000
--- a/docs/src/content/ko/components/click.mdx
+++ /dev/null
@@ -1,85 +0,0 @@
-# Click
-
-클릭 이벤트(`type="onClick"`)를 위한 `DOMEvent`의 특수 버전입니다.
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-const [Track] = createTracker({
- DOMEvents: {
- onClick: (params, context) => {
- // 클릭 이벤트 처리
- },
- },
-});
-
-function App() {
- return (
-
-
-
-
-
- );
-}
-```
-
-### Props
-
-- 스키마와 함께 사용하는 경우
- - `params: SchemaParams | (context: Context) => SchemaParams` - 스키마 기반 클릭 이벤트 매개변수
- - `schema: string` - 이벤트 매개변수 검증을 위한 스키마 이름
-- 스키마와 함께 사용하지 않는 경우
- - `params: EventParams | (context: Context) => EventParams` - 클릭 이벤트 매개변수
-- `enabled?: boolean | ((context: Context, params: EventParams) => boolean)` - 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
-- `debounce?: DebounceConfig` - 연속적인 이벤트 발생을 방지하는 디바운스 설정
-- `throttle?: ThrottleConfig` - 이벤트 발생 빈도를 제한하는 스로틀 설정
-
-**참고:** `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다.
-
-### 추적 옵션 예제
-
-#### 조건부 추적
-
-```tsx
- context.user?.isPremium}>
-
-
-```
-
-#### 디바운스 추적
-
-```tsx
-
-
-
-```
-
-#### 스로틀 추적
-
-```tsx
-
-
-
-```
-
-## 이벤트 이름을 변경한 경우
-
-`eventName` 속성을 사용하면 사용자 정의 클릭 이벤트 핸들러 이름을 지정할 수 있습니다.
-이 속성을 사용하면 핸들러 이름이 변경되어도 유연하게 대처할 수 있습니다.
-
-```tsx {8, 10}
-function MyButton({ onButtonClick }: { onButtonClick?: () => void }) {
- return ;
-}
-
-function App() {
- return (
-
-
-
-
-
- );
-}
-```
diff --git a/docs/src/content/ko/components/dom-event.mdx b/docs/src/content/ko/components/dom-event.mdx
deleted file mode 100644
index fdc0149..0000000
--- a/docs/src/content/ko/components/dom-event.mdx
+++ /dev/null
@@ -1,94 +0,0 @@
-# DOMEvent
-
-DOM 이벤트를 추적하는 데 사용됩니다. 자식 컴포넌트를 감싸고 지정된 이벤트 핸들러를 실행합니다.
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-const [Track] = createTracker({
- DOMEvents: {
- onFocus: (params, context) => {
- // 포커스 이벤트 처리
- },
- },
-});
-
-function App() {
- return (
-
-
-
-
-
- );
-}
-```
-
-### Props
-
-- `type: DOMEventNames` - 이벤트 이름 (예: onClick, onFocus)
-- 스키마와 함께 사용하는 경우
- - `params: SchemaParams | (context: Context) => SchemaParams` - 스키마 기반 매개변수
- - `schema: string` - 이벤트 매개변수 검증을 위한 스키마 이름
-- 스키마와 함께 사용하지 않는 경우
- - `params: EventParams | (context: Context) => EventParams` - 이벤트 매개변수
-- `enabled?: boolean | ((context: Context, params: EventParams) => boolean)` - 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
-- `debounce?: DebounceConfig` - 연속적인 이벤트 발생을 방지하는 디바운스 설정
-- `throttle?: ThrottleConfig` - 이벤트 발생 빈도를 제한하는 스로틀 설정
-
-**참고:** `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다.
-
-### 추적 옵션 예제
-
-#### 조건부 추적
-
-```tsx
- context.trackingEnabled}>
-
-
-```
-
-#### 디바운스 추적
-
-```tsx
-
-
-
-```
-
-#### 스로틀 추적
-
-```tsx
-
-
스크롤 가능한 콘텐츠
-
-```
-
-## 이벤트 이름을 변경한 경우
-
-`eventName` 속성을 사용하면 사용자 정의 이벤트 핸들러 이름을 지정할 수 있습니다.
-이 속성을 사용하면 핸들러 이름이 변경되어도 유연하게 대처할 수 있습니다.
-
-```tsx {8, 10}
-function MyInput({ onInputFocus }: { onInputFocus?: () => void }) {
- return ;
-}
-
-function App() {
- return (
-
-
-
-
-
- );
-}
-```
diff --git a/docs/src/content/ko/components/impression.mdx b/docs/src/content/ko/components/impression.mdx
deleted file mode 100644
index d664b5c..0000000
--- a/docs/src/content/ko/components/impression.mdx
+++ /dev/null
@@ -1,68 +0,0 @@
-# Impression
-
-Intersection Observer API를 사용하여 노출 이벤트를 추적합니다.
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-const [Track] = createTracker({
- impression: {
- onImpression: (params, context) => {
- // 노출 이벤트 처리
- },
- options: {
- threshold: 0.5,
- },
- },
-});
-
-function App() {
- return (
-
-
-
추적할 콘텐츠
-
-
- );
-}
-```
-
-### Props
-
-- `options?: ImpressionOptions` - 선택적 설정 (전역 옵션을 덮어씀)
-- 스키마와 함께 사용하는 경우
- - `params: SchemaParams | (context: Context) => SchemaParams` - 스키마 기반 노출 이벤트 매개변수
- - `schema: string` - 이벤트 매개변수 검증을 위한 스키마 이름
-- 스키마와 함께 사용하지 않는 경우
- - `params: EventParams | (context: Context) => EventParams` - 노출 이벤트 매개변수
-- `enabled?: boolean | ((context: Context, params: EventParams) => boolean)` - 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
-- `debounce?: DebounceConfig` - 연속적인 이벤트 발생을 방지하는 디바운스 설정
-- `throttle?: ThrottleConfig` - 이벤트 발생 빈도를 제한하는 스로틀 설정
-
-**참고:** `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다.
-
-### 추적 옵션 예제
-
-#### 조건부 추적
-
-```tsx
- context.user?.hasAccess}
- options={{ threshold: 0.5 }}
->
-
프리미엄 콘텐츠
-
-```
-
-#### 스로틀 노출 추적
-
-```tsx
-
-
광고 배너
-
-```
diff --git a/docs/src/content/ko/components/index.mdx b/docs/src/content/ko/components/index.mdx
deleted file mode 100644
index 2189f78..0000000
--- a/docs/src/content/ko/components/index.mdx
+++ /dev/null
@@ -1,21 +0,0 @@
-# Provider
-
-`Provider` 컴포넌트는 애플리케이션에 초기 컨텍스트를 연결하고 제공합니다.
-
-```tsx
-import { createTracker } from '@offlegacy/event-tracker'
-
-const [Track] = createTracker({...})
-
-function App() {
- return (
-
- {/* 애플리케이션 컨텐츠 */}
-
- )
-}
-```
-
-### Props
-
-- `initialContext?: Context` - 초기 컨텍스트 값
diff --git a/docs/src/content/ko/components/page-view.mdx b/docs/src/content/ko/components/page-view.mdx
deleted file mode 100644
index 507cad1..0000000
--- a/docs/src/content/ko/components/page-view.mdx
+++ /dev/null
@@ -1,53 +0,0 @@
-# PageView
-
-컴포넌트가 마운트될 때 페이지 뷰 이벤트를 추적합니다.
-
-```tsx
-import { createTracker } from "@offlegacy/event-tracker";
-
-const [Track] = createTracker({
- pageView: {
- onPageView: (params, context) => {
- // 페이지 뷰 이벤트 처리
- },
- },
-});
-
-function App() {
- return (
-
-
-
- );
-}
-```
-
-### Props
-
-- 스키마와 함께 사용하는 경우
- - `params: SchemaParams | (context: Context) => SchemaParams` - 스키마 기반 페이지 뷰 이벤트 매개변수
- - `schema: string` - 이벤트 매개변수 검증을 위한 스키마 이름
-- 스키마와 함께 사용하지 않는 경우
- - `params: EventParams | (context: Context) => EventParams` - 페이지 뷰 이벤트 매개변수
-- `enabled?: boolean | ((context: Context, params: EventParams) => boolean)` - 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
-- `debounce?: DebounceConfig` - 연속적인 이벤트 발생을 방지하는 디바운스 설정
-- `throttle?: ThrottleConfig` - 이벤트 발생 빈도를 제한하는 스로틀 설정
-
-**참고:** `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다.
-
-### 추적 옵션 예제
-
-#### 조건부 추적
-
-```tsx
- context.trackingConsent === true}
-/>
-```
-
-#### 디바운스 페이지 뷰
-
-```tsx
-
-```
diff --git a/docs/src/content/ko/components/set-context.mdx b/docs/src/content/ko/components/set-context.mdx
deleted file mode 100644
index 543639e..0000000
--- a/docs/src/content/ko/components/set-context.mdx
+++ /dev/null
@@ -1,23 +0,0 @@
-# SetContext
-
-트래킹 컨텍스트를 설정하거나 업데이트합니다.
-
-```tsx
-import { createTracker } from '@offlegacy/event-tracker'
-
-const [Track] = createTracker({...})
-
-function App() {
- return (
-
-
-
- )
-}
-```
-
-### Props
-
-- `context: Context | ((prevContext: Context) => Context)` - New context value or update function
diff --git a/docs/src/content/ko/create-tracker.mdx b/docs/src/content/ko/create-tracker.mdx
deleted file mode 100644
index 5b6cbed..0000000
--- a/docs/src/content/ko/create-tracker.mdx
+++ /dev/null
@@ -1,113 +0,0 @@
-# createTracker(config)
-
-원하는 구성으로 트래커 인스턴스를 생성하는 메인 함수입니다.
-
-```tsx
-const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }, useTracker] = createTracker({
- init,
- send,
- DOMEvents,
- impression: {
- onImpression,
- options,
- },
- pageView: {
- onPageView,
- },
- batch,
- schemas,
-});
-```
-
-### 구성 옵션
-
-#### init
-
-- Type: `(initialContext: Context, setContext: SetContext) => void | Promise`
-- 옵셔널
-- 모든 이벤트가 발생하기 전에 실행되는 함수
-- Promise를 반환하면 이벤트가 Promise가 해결될 때까지 지연됩니다.
-
-#### send
-
-- Type: `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
-- 옵셔널
-- 이벤트를 보내는 표준 함수
-- Promise를 반환하면 이벤트가 Promise가 해결될 때까지 지연됩니다.
-
-#### DOMEvents
-
-- Type: `DOMEvents`
-- 옵셔널
-- 표준 React DOM 이벤트 (`onClick`, `onMouseEnter`, 등)의 모음
-- 각 핸들러는 ``에서 해당 이벤트가 발생할 때 실행됩니다.
-- 핸들러가 Promise를 반환하면 후속 이벤트 콜백이 해결될 때까지 지연됩니다.
-
-#### impression
-
-노출 이벤트를 트래킹하기 위한 설정입니다.
-
-- onImpression
-
- - Type: `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
- - Optional
- - Executed when impression occurs on a `` child
- - Promise return value will delay subsequent callbacks
-
-- options
- - Type: `ImpressionOptions`
- - 옵셔널
- - 노출 이벤트 트래킹 구성 옵션:
- - `threshold`: 노출 필요 비율 (기본값: 0.2)
- - `freezeOnceVisible`: 노출 후 교차 상태 고정 (기본값: true)
- - `initialIsIntersecting`: 초기 교차 상태 (기본값: false)
-
-#### pageView
-
-페이지 뷰 이벤트를 트래킹하기 위한 설정입니다.
-
-##### onPageView
-
-- Type: `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
-- 옵셔널
-- ``가 마운트될 때 실행됩니다.
-- Promise를 반환하면 후속 이벤트가 해결될 때까지 지연됩니다.
-
-#### batch
-
-이벤트 배칭을 위한 설정입니다.
-
-- Type: `BatchConfig`
-- 옵셔널
-- Properties:
- - `enable`: 배칭 활성화 (기본값: false)
- - `interval`: 버퍼링 간격 (ms) (기본값: 3000)
- - `thresholdSize`: 최대 배칭 크기 (기본값: 25)
- - `onFlush`: 배치 비우기 처리 함수 (활성화된 경우 필요)
- - `onError`: 오류 처리 함수 (옵셔널)
-
-#### schemas
-
-데이터 타입 검증을 위한 설정입니다.
-
-- Type: `SchemaConfig`
-- 옵셔널
-- Properties:
- - `schemas`: [Zod](https://zod.dev/) 스키마의 레코드
- - `onSchemaError`?: 스키마 검증 오류 처리 함수
- - `abortOnError`?: 스키마 검증 오류가 발생한 경우 이벤트 추적 중단 여부 (기본값: false)
-
-### Return Value
-
-`createTracker` 함수는 다음 튜플을 반환합니다:
-
-1. 트래킹 컴포넌트를 포함하는 객체:
-
- - [`Provider`](/docs/components)
- - [`DOMEvent`](/docs/components/dom-event)
- - [`Click`](/docs/components/click)
- - [`Impression`](/docs/components/impression)
- - [`PageView`](/docs/components/page-view)
- - [`SetContext`](/docs/components/set-context)
-
-2. [커스텀 hook](/docs/hook)
diff --git a/docs/src/content/ko/data-type-validation.mdx b/docs/src/content/ko/data-type-validation.mdx
deleted file mode 100644
index 14a4eeb..0000000
--- a/docs/src/content/ko/data-type-validation.mdx
+++ /dev/null
@@ -1,69 +0,0 @@
-# 데이터 타입 검증
-
-## 소개
-
-이벤트 트래킹에서 정확한 데이터 타입을 확인하는 것은 데이터 신뢰성과 의미 있는 분석을 위해 매우 중요합니다.
-`event-tracker`는 [Zod](https://zod.dev/)를 사용하여 내장된 데이터 타입 검증을 제공합니다.
-이 기능을 사용하면 이벤트 매개변수에 대한 스키마를 정의할 수 있으며, 데이터가 처리되기 전에 예상되는 데이터 타입과 일치하는지 확인할 수 있습니다.
-이는 이벤트 트래킹에서 일관성을 유지하고 오류를 방지하는 데 매우 유용합니다.
-
-## 설정
-
-`event-tracker`에서 데이터 타입 검증을 구성하려면 Zod를 사용하여 스키마를 정의하고 트래커 설정에 전달해야 합니다.
-
-### 옵션
-
-- **schemas**: Zod 스키마의 레코드로, 이벤트 매개변수의 구조를 정의합니다.
-- **onSchemaError**: 스키마 검증이 실패할 때 호출되는 콜백 함수입니다.
-- **abortOnError**: 스키마 검증 오류가 발생할 때 이벤트 처리를 중단할지 여부를 나타내는 부울 값입니다. 기본값은 `false`입니다.
-
-## 예시
-
-1. **스키마 정의**: Zod를 사용하여 이벤트 매개변수의 예상 구조를 정의합니다.
-
- ```typescript
- import { z } from "zod";
-
- const page_view = z.object({
- title: z.string(),
- });
-
- const click_button = z.object({
- target: z.string(),
- });
- ```
-
-2. **트래커 설정**: `createTracker` 함수에 스키마를 전달합니다.
-
- ```tsx
- import { createTracker } from "@offlegacy/event-tracker";
-
- const schemas = {
- page_view;
- clic_button;
- };
-
- const [Track] = createTracker<{}, {}, typeof schemas>({
- schema: {
- schemas,
- onSchemaError: (error) => {
- console.error("Schema validation error:", error);
- },
- abortOnError: true,
- },
- // other configurations...
- });
- ```
-
-3. **이벤트 검증**: 이벤트가 추적될 때, 정의된 스키마에 대해 검증됩니다. 또한 TypeScript를 사용하여 사전에 검증됩니다.
- ```tsx
-
-
- ```
-
-## 유의 사항
-
-- Zod 스키마는 기본적으로 [`.parse()`](https://zod.dev/?id=parse)를 사용하여 검증됩니다.
-- 부드러운 타입 추론을 위해, `createTracker` 함수 외부에서 스키마를 정의하고 `createTracker`의 세 번째 타입 인자에 `typeof schemas`를 할당하길 권장합니다.
-
-_향후 다른 스키마 검증 라이브러리를 지원할 계획입니다._
diff --git a/docs/src/content/ko/docs/_meta.ts b/docs/src/content/ko/docs/_meta.ts
new file mode 100644
index 0000000..bb305a6
--- /dev/null
+++ b/docs/src/content/ko/docs/_meta.ts
@@ -0,0 +1,92 @@
+import type { MetaRecord } from "nextra";
+
+export default {
+ "getting-started-separator": {
+ type: "separator",
+ title: "시작하기",
+ },
+ introduction: {
+ title: "소개",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ "why-event-tracker": {
+ title: "왜 Event Tracker인가요?",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ installation: {
+ title: "설치하기",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ // TODO: Quick Start
+ "api-reference-separator": {
+ title: "API 레퍼런스",
+ type: "separator",
+ },
+ "create-tracker": {
+ title: "createTracker",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ components: { title: "Components" },
+ hook: {
+ title: "Hook",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ "advanced-separator": {
+ title: "가이드",
+ type: "separator",
+ },
+ batching: {
+ title: "배칭",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ "data-type-validation": {
+ title: "데이터 검증",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ "example-separator": {
+ title: "예제",
+ type: "separator",
+ },
+ "basic-example": {
+ title: "기본",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ "with-google-analytics-example": {
+ title: "Google Analytics 연동하기",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+ "with-zod-example": {
+ title: "Zod와 함께 사용하기",
+ theme: {
+ toc: true,
+ layout: "default",
+ },
+ },
+} satisfies MetaRecord;
diff --git a/docs/src/content/ko/docs/basic-example.mdx b/docs/src/content/ko/docs/basic-example.mdx
new file mode 100644
index 0000000..cb40094
--- /dev/null
+++ b/docs/src/content/ko/docs/basic-example.mdx
@@ -0,0 +1,75 @@
+import { Steps } from "nextra/components";
+
+# 기본
+
+Event Tracker 라이브러리의 전체 흐름과 사용방법을 단계별로 살펴봅니다.
+각 단계별로 필요한 설정과 컴포넌트 사용법, 그리고 이벤트 처리 과정을 이해할 수 있도록 구성했습니다.
+
+
+
+## 트래킹 이벤트 정의하기
+
+Tracker 인스턴스를 생성하고, DOM 이벤트에 대한 콜백을 정의합니다.
+
+```tsx {12}
+import { createTracker } from "@offlegacy/event-tracker";
+
+interface Context {
+ userId: string;
+}
+
+interface Params {
+ eventName: string;
+}
+
+// 트래커 인스턴스 생성
+export const [Track, useTracker] = createTracker({
+ // 트래킹 이벤트 정의
+ DOMEvents: {
+ onClick: (params: Params) => {
+ console.log("click:", params);
+ },
+ },
+});
+```
+
+## Provider 추가하기
+
+애플리케이션 최상단에 `Track.Provider`를 추가하고 전역 컨텍스트를 설정합니다.
+
+```tsx {5, 7}
+import { Track, useTracker } from "./tracker";
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## 정의한 이벤트 사용하기
+
+`Track.Click` 컴포넌트를 이용해 선언적으로 클릭 이벤트를 트래킹합니다.
+
+```tsx {7-11, 13}
+function HomePage() {
+ return (
+
+
홈페이지
+
+ {/* 버튼 클릭 트래킹 */}
+
+
+
+
+ );
+}
+```
+
+
diff --git a/docs/src/content/ko/docs/batching.mdx b/docs/src/content/ko/docs/batching.mdx
new file mode 100644
index 0000000..656ffcb
--- /dev/null
+++ b/docs/src/content/ko/docs/batching.mdx
@@ -0,0 +1,129 @@
+import { Callout } from "nextra/components";
+
+# 배칭
+
+이벤트 배칭은 여러 개의 이벤트를 일정 조건 하에 하나의 네트워크 요청으로 묶어 전송하는 기능입니다. 다음과 같은 경우에 유용하게 사용할 수 있습니다.
+
+- Amplitude, Google Analytics 등 내부 배칭 기능이 없는 애널리틱스 서비스를 사용하는 경우
+- 네트워크 요청 수를 줄이고 싶은 경우
+- 브라우저 종료 시 이벤트 유실을 방지하고 싶은 경우
+
+## Usage
+
+`createTracker` 설정에서 `batch` 옵션을 활성화하면 사용할 수 있습니다.
+
+```tsx
+const [Track, useTracker] = createTracker({
+ // ... 다른 설정
+ batch: {
+ enable: true,
+ interval: 2000,
+ thresholdSize: 100,
+ onFlush: (batch, isBrowserClosing) => {
+ if (isBrowserClosing) {
+ navigator.sendBeacon("/analytics/collect/batch", JSON.stringify(batch));
+ return;
+ }
+
+ fetch("/analytics/collect/batch", {
+ method: "POST",
+ body: JSON.stringify(batch),
+ });
+ },
+ },
+});
+```
+
+## Options
+
+| 옵션 | 타입 | 설명 | 기본값 |
+| --------------- | ---------------------------------------------------- | ------------------------------------------ | ------- |
+| `enable` | `boolean` | 배칭 기능 활성화 여부 | `false` |
+| `interval` | `number` | 배치 전송 간격 (밀리초 단위) | `3000` |
+| `thresholdSize` | `number` | 배치 전송 전에 쌓일 수 있는 최대 이벤트 수 | `25` |
+| `onFlush` | `(batch, isBrowserClosing) => void \| Promise` | 배치 전송 처리 함수. 필수 | - |
+| `onError` | `(error: Error) => void \| Promise` | 전송 중 오류 발생 시 호출되는 함수 (선택) | - |
+
+`onFlush`는 **필수 항목**이며, 배치된 이벤트를 실제로 어떻게 전송할지를 정의합니다.
+
+## How It Works
+
+1. 각 이벤트의 **핸들러 반환값**은 메모리에 수집됩니다.
+2. 아래 중 하나가 발생하면 `onFlush`가 호출됩니다:
+
+ - `interval` 시간이 경과했을 때
+ - 수집된 이벤트 수가 `thresholdSize`에 도달했을 때
+ - 브라우저가 닫히는 이벤트가 감지되었을 때
+
+## Examples
+
+```tsx
+const [Track, useTracker] = createTracker({
+ DOMEvents: {
+ onClick: (params, context) => {
+ return {
+ ...params,
+ ...context,
+ event_type: "click",
+ timestamp: Date.now(),
+ };
+ },
+ },
+ batch: {
+ enable: true,
+ interval: 2000,
+ thresholdSize: 100,
+ onFlush: (batch, isBrowserClosing) => {
+ if (isBrowserClosing) {
+ navigator.sendBeacon("/analytics/collect/batch", JSON.stringify(batch));
+ return;
+ }
+
+ fetch("/analytics/collect/batch", {
+ method: "POST",
+ body: JSON.stringify(batch),
+ });
+ },
+ },
+});
+
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+1. ``이 실행될 때마다 이벤트 핸들러가 반환하는 객체가 배치 큐에 저장됩니다.
+2. 2초 후 또는 100개의 이벤트가 쌓이면 `onFlush`가 호출되어 서버로 전송됩니다.
+3. 브라우저가 닫히는 시점에서는 `sendBeacon`으로 전송됩니다.
+
+## 브라우저 종료 시 처리
+
+브라우저가 닫힐 때도 이벤트 유실을 방지하기 위해
+[`navigator.sendBeacon`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)을 활용할 수 있습니다:
+
+```tsx
+onFlush: (batch, isBrowserClosing) => {
+ if (isBrowserClosing) {
+ navigator.sendBeacon("/analytics/collect/batch", JSON.stringify(batch));
+ return;
+ }
+
+ fetch("/analytics/collect/batch", {
+ method: "POST",
+ body: JSON.stringify(batch),
+ });
+};
+```
+
+## Notes
+
+1. **이벤트 핸들러의 반환값만 배칭됩니다.** 이벤트 핸들러 자체는 항상 호출됩니다.
+2. **배치된 이벤트는 컨텍스트 정보를 포함한 상태로 저장됩니다.**
+3. **전송 순서를 보장합니다.** 클릭 → 노출 순으로 발생한 이벤트는 그 순서대로 전송됩니다.
+4. 브라우저 종료 시 `isBrowserClosing` 플래그가 `true`로 설정되어 `onFlush`에서 분기 처리할 수 있습니다.
diff --git a/docs/src/content/ko/components/_meta.ts b/docs/src/content/ko/docs/components/_meta.ts
similarity index 100%
rename from docs/src/content/ko/components/_meta.ts
rename to docs/src/content/ko/docs/components/_meta.ts
diff --git a/docs/src/content/ko/docs/components/click.mdx b/docs/src/content/ko/docs/components/click.mdx
new file mode 100644
index 0000000..d4c1784
--- /dev/null
+++ b/docs/src/content/ko/docs/components/click.mdx
@@ -0,0 +1,138 @@
+import { Callout } from "nextra/components";
+
+# Click
+
+Click 이벤트(`type="onClick"`)를 위한 `DOMEvent`의 전용 컴포넌트입니다. `createTracker`의 리턴 배열의 첫 번쨰 요소인 이벤트 컴포넌트 중 하나입니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({
+ DOMEvents: {
+ onClick: (params, context) => {
+ // 클릭 이벤트 처리
+ },
+ },
+});
+
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Props | 타입 | 설명 | 필수 |
+| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------- | ---- |
+| `enabled` | `boolean \| ((context: Context, params: EventParams) => boolean)` | 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`) | - |
+| `debounce` | `DebounceConfig` | 연속적인 이벤트 발생을 방지하는 디바운스 설정 | - |
+| `throttle` | `ThrottleConfig` | 이벤트 발생 빈도를 제한하는 스로틀 설정 | - |
+| `schema` | `string` | 이벤트 매개변수 검증을 위한 스키마 이름 | O |
+
+
+ 참고: `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다. 타입 에러를 발생시켜 사전에 방지합니다.
+
+
+스키마와 함께 사용하는 경우와 아닐 경우 타입이 달라지는 속성이 있습니다.
+
+스키마가 있을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | ---------------------------------------------------- | -------------------- |
+| `params` | `SchemaParams \| (context: Context) => SchemaParams` | 스키마 기반 매개변수 |
+
+스키마가 없을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | -------------------------------------------------- | --------------- |
+| `params` | `EventParams \| (context: Context) => EventParams` | 이벤트 매개변수 |
+
+---
+
+#### `params` (필수)
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `SchemaParams | (context: Context) => SchemaParams`
+- 설명: 스키마 기반 매개변수
+
+스키마와 함께 사용하지 않는 경우:
+
+- 타입: `EventParams | (context: Context) => EventParams`
+- 설명: 이벤트 매개변수
+
+#### `enabled`
+
+- 타입: `boolean | ((context: Context, params: EventParams) => boolean)`
+- 설명: 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
+
+#### `debounce`
+
+- 타입: `DebounceConfig`
+- 설명: 연속적인 이벤트 발생을 방지하는 디바운스 설정
+
+#### `throttle`
+
+- 타입: `ThrottleConfig`
+- 설명: 이벤트 발생 빈도를 제한하는 스로틀 설정
+
+#### `schema`
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `string`
+- 설명: 이벤트 매개변수 검증을 위한 스키마 이름
+
+## Examples
+
+### 이벤트 이름을 변경한 경우
+
+```tsx {8, 10}
+function MyButton({ onButtonClick }: { onButtonClick?: () => void }) {
+ return ;
+}
+
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+`eventName` 속성을 사용하면 사용자 정의 클릭 이벤트 핸들러 이름을 지정할 수 있습니다. 이 속성을 사용하면 핸들러 이름이 변경되어도 유연하게 대처할 수 있습니다.
+
+### 조건부 이벤트
+
+```tsx
+ context.user?.isPremium}>
+
+
+```
+
+### 디바운스 이벤트
+
+```tsx
+
+
+
+```
+
+### 스로틀 이벤트
+
+```tsx
+
+
+
+```
diff --git a/docs/src/content/ko/docs/components/dom-event.mdx b/docs/src/content/ko/docs/components/dom-event.mdx
new file mode 100644
index 0000000..cdf6ddd
--- /dev/null
+++ b/docs/src/content/ko/docs/components/dom-event.mdx
@@ -0,0 +1,147 @@
+import { Callout } from "nextra/components";
+
+# DOMEvent
+
+DOM 이벤트를 추적하는 데 사용됩니다. 자식 컴포넌트를 감싸고 지정된 이벤트 핸들러를 실행합니다. `createTracker`의 리턴 배열의 첫 번쨰 요소인 이벤트 컴포넌트 중 하나입니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({
+ DOMEvents: {
+ onFocus: (params, context) => {
+ // 포커스 이벤트 처리
+ },
+ },
+});
+
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Props | 타입 | 설명 | 필수 |
+| ------------- | ----------------------------------------------------------------- | ------------------------------------------------------- | ---- |
+| DOMEventNames | DOMEventNames | 이벤트 이름 (예: `"onClick"`, `"onFocus"`) | O |
+| `enabled` | `boolean \| ((context: Context, params: EventParams) => boolean)` | 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`) | - |
+| `debounce` | `DebounceConfig` | 연속적인 이벤트 발생을 방지하는 디바운스 설정 | - |
+| `throttle` | `ThrottleConfig` | 이벤트 발생 빈도를 제한하는 스로틀 설정 | - |
+| `schema` | `string` | 이벤트 매개변수 검증을 위한 스키마 이름 | - |
+
+
+ 참고: `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다. 타입 에러를 발생시켜 사전에 방지합니다.
+
+
+스키마와 함께 사용하는 경우와 아닐 경우 타입이 달라지는 속성이 있습니다.
+
+스키마가 있을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | ---------------------------------------------------- | -------------------- |
+| `params` | `SchemaParams \| (context: Context) => SchemaParams` | 스키마 기반 매개변수 |
+
+스키마가 없을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | -------------------------------------------------- | --------------- |
+| `params` | `EventParams \| (context: Context) => EventParams` | 이벤트 매개변수 |
+
+---
+
+#### `params` (필수)
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `SchemaParams | (context: Context) => SchemaParams`
+- 설명: 스키마 기반 매개변수
+
+스키마와 함께 사용하지 않는 경우:
+
+- 타입: `EventParams | (context: Context) => EventParams`
+- 설명: 이벤트 매개변수
+
+#### `enabled`
+
+- 타입: `boolean | ((context: Context, params: EventParams) => boolean)`
+- 설명: 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
+
+#### `debounce`
+
+- 타입: `DebounceConfig`
+- 설명: 연속적인 이벤트 발생을 방지하는 디바운스 설정
+
+#### `throttle`
+
+- 타입: `ThrottleConfig`
+- 설명: 이벤트 발생 빈도를 제한하는 스로틀 설정
+
+#### `schema`
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `string`
+- 설명: 이벤트 매개변수 검증을 위한 스키마 이름
+
+## Examples
+
+### 이벤트 이름을 변경한 경우
+
+```tsx {8, 10}
+function MyInput({ onInputFocus }: { onInputFocus?: () => void }) {
+ return ;
+}
+
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+`eventName` 속성을 사용하면 사용자 정의 이벤트 핸들러 이름을 지정할 수 있습니다. 이 속성을 사용하면 핸들러 이름이 변경되어도 유연하게 대처할 수 있습니다.
+
+### 조건부 이벤트
+
+```tsx
+ context.trackingEnabled}>
+
+
+```
+
+### 디바운스 이벤트
+
+```tsx
+
+
+
+```
+
+### 스로틀 이벤트
+
+```tsx
+
+
스크롤 가능한 콘텐츠
+
+```
diff --git a/docs/src/content/ko/docs/components/impression.mdx b/docs/src/content/ko/docs/components/impression.mdx
new file mode 100644
index 0000000..6f5f89f
--- /dev/null
+++ b/docs/src/content/ko/docs/components/impression.mdx
@@ -0,0 +1,128 @@
+import { Callout } from "nextra/components";
+
+# Impression
+
+[Intersection Observer API](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API)를 사용하여 노출 이벤트를 추적합니다. `createTracker`의 리턴 배열의 첫 번째 요소인 이벤트 컴포넌트 중 하나입니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({
+ impression: {
+ onImpression: (params, context) => {
+ // 노출 이벤트 처리
+ },
+ options: {
+ threshold: 0.5,
+ },
+ },
+});
+
+function App() {
+ return (
+
+
+
추적할 콘텐츠
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Props | 타입 | 설명 | 필수 |
+| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------- | ---- |
+| `enabled` | `boolean \| ((context: Context, params: EventParams) => boolean)` | 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`) | - |
+| `debounce` | `DebounceConfig` | 연속적인 이벤트 발생을 방지하는 디바운스 설정 | - |
+| `throttle` | `ThrottleConfig` | 이벤트 발생 빈도를 제한하는 스로틀 설정 | - |
+| `options` | `ImpressionOptions` | `IntersectionObserver` 설정. 전역 옵션을 덮어씀 | - |
+| `schema` | `string` | 이벤트 매개변수 검증을 위한 스키마 이름 | O |
+
+
+ 참고: `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다. 타입 에러를 발생시켜 사전에 방지합니다.
+
+
+스키마와 함께 사용하는 경우와 아닐 경우 타입이 달라지는 속성이 있습니다.
+
+스키마가 있을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | ---------------------------------------------------- | -------------------- |
+| `params` | `SchemaParams \| (context: Context) => SchemaParams` | 스키마 기반 매개변수 |
+
+스키마가 없을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | -------------------------------------------------- | --------------- |
+| `params` | `EventParams \| (context: Context) => EventParams` | 이벤트 매개변수 |
+
+---
+
+#### `params` (필수)
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `SchemaParams | (context: Context) => SchemaParams`
+- 설명: 스키마 기반 매개변수
+
+스키마와 함께 사용하지 않는 경우:
+
+- 타입: `EventParams | (context: Context) => EventParams`
+- 설명: 이벤트 매개변수
+
+#### `enabled`
+
+- 타입: `boolean | ((context: Context, params: EventParams) => boolean)`
+- 설명: 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
+
+#### `debounce`
+
+- 타입: `DebounceConfig`
+- 설명: 연속적인 이벤트 발생을 방지하는 디바운스 설정
+
+#### `throttle`
+
+- 타입: `ThrottleConfig`
+- 설명: 이벤트 발생 빈도를 제한하는 스로틀 설정
+
+#### `options`
+
+- 타입: `ImpressionOptions`
+- 설명: [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) 동작을 제어하는 옵션입니다. 예: `threshold`, `rootMargin` 등
+ 전역 설정을 덮어쓰며 개별 노출 이벤트에 대해 세부 설정할 수 있습니다.
+
+#### `schema`
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `string`
+- 설명: 이벤트 매개변수 검증을 위한 스키마 이름
+
+## Examples
+
+### 조건부 이벤트
+
+```tsx
+ context.user?.hasAccess}
+ options={{ threshold: 0.5 }}
+>
+
프리미엄 콘텐츠
+
+```
+
+### 스로틀 이벤트
+
+```tsx
+
+
광고 배너
+
+```
diff --git a/docs/src/content/ko/docs/components/index.mdx b/docs/src/content/ko/docs/components/index.mdx
new file mode 100644
index 0000000..137c84b
--- /dev/null
+++ b/docs/src/content/ko/docs/components/index.mdx
@@ -0,0 +1,63 @@
+# Provider
+
+`Provider` 컴포넌트는 애플리케이션에 초기 컨텍스트를 연결하고 제공합니다. `createTracker`의 리턴 배열의 첫 번쨰 요소인 이벤트 컴포넌트 중 하나입니다.
+
+```tsx
+import { createTracker } from '@offlegacy/event-tracker'
+
+const [Track] = createTracker({...})
+
+function App() {
+ return (
+
+ {/* 애플리케이션 */}
+
+ )
+}
+```
+
+## Reference
+
+### Props
+
+| Props | 타입 | 설명 | 필수 |
+| ---------------- | --------- | ---------------- | ---- |
+| `initialContext` | `Context` | 초기 컨텍스트 값 | O |
+
+---
+
+#### `initialContext` (필수)
+
+- 타입: `Context`
+- 설명: 초기 컨텍스트 값
+
+## Examples
+
+### 초기 컨텍스트를 설정한 경우
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+type Context = {
+ userId: string;
+ trackingEnabled: boolean;
+};
+
+const [Track] = createTracker({});
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+`initialContext`는 모든 하위 트래킹 컴포넌트에서 참조 가능한 초기 상태를 정의합니다.
+이 컨텍스트는 `enabled`, `params`, 그리고 `SetContext`에서 사용될 수 있습니다.
diff --git a/docs/src/content/ko/docs/components/page-view.mdx b/docs/src/content/ko/docs/components/page-view.mdx
new file mode 100644
index 0000000..9b1c6c1
--- /dev/null
+++ b/docs/src/content/ko/docs/components/page-view.mdx
@@ -0,0 +1,107 @@
+import { Callout } from "nextra/components";
+
+# PageView
+
+컴포넌트가 마운트될 때 페이지 뷰 이벤트를 추적합니다. `createTracker`의 리턴 배열의 첫 번째 요소인 이벤트 컴포넌트 중 하나입니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({
+ pageView: {
+ onPageView: (params, context) => {
+ // 페이지 뷰 이벤트 처리
+ },
+ },
+});
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Props | 타입 | 설명 | 필수 |
+| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------- | ---- |
+| `enabled` | `boolean \| ((context: Context, params: EventParams) => boolean)` | 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`) | - |
+| `debounce` | `DebounceConfig` | 연속적인 이벤트 발생을 방지하는 디바운스 설정 | - |
+| `throttle` | `ThrottleConfig` | 이벤트 발생 빈도를 제한하는 스로틀 설정 | - |
+| `schema` | `string` | 이벤트 매개변수 검증을 위한 스키마 이름 | O |
+
+
+ 참고: `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다. 타입 에러를 발생시켜 사전에 방지합니다.
+
+
+스키마와 함께 사용하는 경우와 아닐 경우 타입이 달라지는 속성이 있습니다.
+
+스키마가 있을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | ---------------------------------------------------- | -------------------- |
+| `params` | `SchemaParams \| (context: Context) => SchemaParams` | 스키마 기반 매개변수 |
+
+스키마가 없을 경우:
+
+| Props | 타입 | 설명 |
+| -------- | -------------------------------------------------- | --------------- |
+| `params` | `EventParams \| (context: Context) => EventParams` | 이벤트 매개변수 |
+
+---
+
+#### `params` (필수)
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `SchemaParams | (context: Context) => SchemaParams`
+- 설명: 스키마 기반 매개변수
+
+스키마와 함께 사용하지 않는 경우:
+
+- 타입: `EventParams | (context: Context) => EventParams`
+- 설명: 이벤트 매개변수
+
+#### `enabled`
+
+- 타입: `boolean | ((context: Context, params: EventParams) => boolean)`
+- 설명: 이벤트 추적을 조건부로 활성화/비활성화 (기본값: `true`)
+
+#### `debounce`
+
+- 타입: `DebounceConfig`
+- 설명: 연속적인 이벤트 발생을 방지하는 디바운스 설정
+
+#### `throttle`
+
+- 타입: `ThrottleConfig`
+- 설명: 이벤트 발생 빈도를 제한하는 스로틀 설정
+
+#### `schema`
+
+스키마와 함께 사용하는 경우:
+
+- 타입: `string`
+- 설명: 이벤트 매개변수 검증을 위한 스키마 이름
+
+## Examples
+
+### 조건부 이벤트
+
+```tsx
+ context.trackingConsent === true}
+/>
+```
+
+### 디바운스 페이지 뷰
+
+```tsx
+
+```
diff --git a/docs/src/content/ko/docs/components/set-context.mdx b/docs/src/content/ko/docs/components/set-context.mdx
new file mode 100644
index 0000000..2e89ee7
--- /dev/null
+++ b/docs/src/content/ko/docs/components/set-context.mdx
@@ -0,0 +1,48 @@
+import { Callout } from "nextra/components";
+
+# SetContext
+
+트래킹 컨텍스트를 설정하거나 업데이트합니다. `createTracker`의 리턴 배열의 첫 번째 요소인 유틸리티 컴포넌트 중 하나입니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+const [Track] = createTracker({ ... });
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Reference
+
+### Props
+
+| Props | 타입 | 설명 | 필수 |
+| --------- | ------------------------------------------------ | ------------------------------------------------------------ | ---- |
+| `context` | `Context \| ((prevContext: Context) => Context)` | 새로운 컨텍스트 값 또는 기존 값을 기반으로 업데이트하는 함수 | O |
+
+---
+
+#### `context` (필수)
+
+- 타입: `Context | ((prevContext: Context) => Context)`
+- 설명: 새 컨텍스트 값을 직접 지정하거나, 이전 컨텍스트 값을 기반으로 업데이트할 수 있습니다. 이 컴포넌트는 한 번 렌더링되면 지정된 컨텍스트로 추적 컨텍스트가 갱신됩니다.
+
+## Examples
+
+### 정적 컨텍스트 설정
+
+```tsx
+
+```
+
+### 이전 컨텍스트 기반 업데이트
+
+```tsx
+ ({ ...prev, lastSeen: new Date() })} />
+```
diff --git a/docs/src/content/ko/docs/create-tracker.mdx b/docs/src/content/ko/docs/create-tracker.mdx
new file mode 100644
index 0000000..6a540b8
--- /dev/null
+++ b/docs/src/content/ko/docs/create-tracker.mdx
@@ -0,0 +1,127 @@
+# createTracker
+
+`createTracker`는 사용자 정의 설정으로 트래커 인스턴스를 생성하는 함수입니다. 이 함수의 파라미터를 통해 이벤트 트래킹을 정의하고, 반환된 튜플을 통해 트래커 인스턴스를 사용할 수 있습니다.
+
+```tsx
+const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }, useTracker] = createTracker({
+ init,
+ send,
+ DOMEvents,
+ impression: {
+ onImpression,
+ options,
+ },
+ pageView: {
+ onPageView,
+ },
+ batch,
+ schemas,
+});
+```
+
+## Reference
+
+### Parameters
+
+`createTracker`는 하나의 객체를 인자로 받습니다.
+
+| 속성 (Property) | 타입 | 설명 |
+| --------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- |
+| `init` | `(initialContext: Context, setContext: SetContext) => void \| Promise` | 모든 이벤트 발생 전에 실행되는 초기화 함수. (비동기 지원) |
+| `send` | `(params: EventParams \| (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType` | 이벤트 전송 함수. (비동기 지원) |
+| `DOMEvents` | [`DOMEvents`](https://developer.mozilla.org/docs/Web/API/Event) | React DOM 이벤트 핸들러 모음 (`onClick`, `onMouseEnter` 등) |
+| `impression` | `ImpressionOptions` | 노출 이벤트 트래킹 설정 |
+| `pageView` | `PageViewOptions` | 페이지 뷰 트래킹 설정 |
+| `batch` | `BatchConfig` | 이벤트 배칭 설정 |
+| `schemas` | `SchemaConfig` | 이벤트 스키마 검증 설정 |
+
+---
+
+#### `init`
+
+- 타입: `(initialContext: Context, setContext: SetContext) => void | Promise`
+- 설명: 모든 이벤트가 발생하기 전, 초기 컨텍스트를 설정하는 함수입니다. (비동기를 지원합니다.)
+
+#### `send`
+
+- 타입: `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
+- 설명: 이벤트를 외부로 전송하는 함수입니다. (비동기를 지원합니다.)
+
+#### `DOMEvents`
+
+- 타입: `DOMEvents`
+- 설명: 표준 React DOM 이벤트 핸들러 객체입니다. `` 컴포넌트에서 사용됩니다.
+
+#### `impression`
+
+- `impression.onImpression`
+
+ - 타입: `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
+ - 설명: `` 발생 시 실행되는 콜백 함수입니다.
+
+- `impression.options`
+
+ - 타입: `ImpressionOptions`
+ - 속성:
+
+ - `threshold`: 노출 비율 기준 (기본값: `0.2`)
+ - `freezeOnceVisible`: 노출 후 상태 고정 여부 (기본값: `true`)
+ - `initialIsIntersecting`: 초기 교차 여부 (기본값: `false`)
+
+#### `pageView`
+
+- `pageView.onPageView`
+
+ - 타입: `(params: EventParams | (context: Context) => EventParams, context: Context, setContext: SetContext) => TaskReturnType`
+ - 설명: `` 컴포넌트가 마운트 시 실행됩니다.
+
+#### `batch`
+
+- 타입: `BatchConfig`
+- 속성:
+
+ - `batch.enable`: 배치 활성화 여부 (기본값: `false`)
+ - `batch.interval`: 전송 간격(ms, 기본값: `3000`)
+ - `batch.thresholdSize`: 최대 배치 크기 (기본값: `25`)
+ - `batch.onFlush`: 이벤트 전송 처리 함수
+ - `batch.onError`: 오류 발생 시 처리 함수 (선택)
+
+#### `schemas`
+
+- 타입: `SchemaConfig`
+- 속성:
+
+ - `schemas.schema`: [Zod](https://zod.dev/) 기반의 스키마 정의
+ - `schemas.onSchemaError`: 스키마 오류 발생 시 처리 함수
+ - `schemas.abortOnError`: 오류 시 이벤트 중단 여부 (기본값: `false`)
+
+### Returns
+
+`createTracker`는 다음 두 값을 포함한 튜플을 반환합니다.
+
+```tsx
+const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }, useTracker] = createTracker({...})
+```
+
+#### [Components](./components)
+
+리턴 배열에서 첫 요소인 이벤트 컴포넌트는 여러 가지 이벤트 컴포넌트를 포함하고 있습니다.
+
+```tsx
+const [{ Provider, DOMEvent, Click, Impression, PageView, SetContext }] = createTracker(config);
+```
+
+- `Provider`
+- `DOMEvent`
+- `Click`
+- `Impression`
+- `PageView`
+- `SetContext`
+
+#### [Hook](./hook)
+
+```tsx
+const [, useTracker] = createTracker(config);
+```
+
+리턴 배열에서 두번째 요소인 커스텀 React hook입니다. 이 훅은 컴포넌트 내에서 이벤트 트래킹 기능과 컨텍스트 관리에 접근할 수 있게 합니다.
diff --git a/docs/src/content/ko/docs/data-type-validation.mdx b/docs/src/content/ko/docs/data-type-validation.mdx
new file mode 100644
index 0000000..9f9a2af
--- /dev/null
+++ b/docs/src/content/ko/docs/data-type-validation.mdx
@@ -0,0 +1,96 @@
+import { Callout, Steps } from "nextra/components";
+
+# 데이터 검증
+
+Event Tracker는 이벤트 파라미터의 정확성을 보장하기 위해 [Zod](https://zod.dev/)를 활용한 스키마 기반 데이터 타입 검증 기능을 제공합니다.
+이 기능을 사용하면 이벤트가 수집되기 전에 사전 정의된 구조와 일치하는지 검증할 수 있으며, 이는 데이터 신뢰성과 오류 방지, 정형 분석을 위한 기반으로 유용합니다.
+
+## Usage
+
+Zod 스키마를 정의하고, `createTracker` 설정에서 `schemas` 옵션으로 전달하면 됩니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+import { z } from "zod";
+
+const schemas = {
+ page_view: z.object({
+ title: z.string(),
+ }),
+ click_button: z.object({
+ target: z.string(),
+ }),
+};
+
+const [Track] = createTracker<{}, {}, typeof schemas>({
+ schemas: {
+ schemas,
+ onSchemaError: (error) => {
+ console.error("스키마 검증 실패:", error);
+ },
+ abortOnError: true,
+ },
+});
+```
+
+## Reference
+
+| 옵션 | 타입 | 설명 | 기본값 |
+| --------------- | -------------------------------------------- | ---------------------------------------- | ------- |
+| `schemas` | `Record` | 이벤트 이름과 Zod 스키마의 매핑 | 필수 |
+| `onSchemaError` | `(error: ZodError) => void \| Promise` | 스키마 검증 실패 시 호출되는 함수 | 선택 |
+| `abortOnError` | `boolean` | 오류 발생 시 이벤트 처리를 중단할지 여부 | `false` |
+
+스키마 오류가 발생했을 때 `abortOnError: true`인 경우, 해당 이벤트는 추적되지 않습니다.
+
+## Examples
+
+
+
+### Zod 스키마 정의
+
+```ts
+import { z } from "zod";
+
+const schemas = {
+ page_view: z.object({
+ title: z.string(),
+ }),
+ click_button: z.object({
+ target: z.string(),
+ }),
+};
+```
+
+### `createTracker`에 등록
+
+```tsx
+const [Track] = createTracker<{}, {}, typeof schemas>({
+ schemas: {
+ schemas,
+ abortOnError: true,
+ onSchemaError: (error) => {
+ console.error("스키마 오류 발생", error);
+ },
+ },
+});
+```
+
+### 스키마 기반 이벤트 트래킹
+
+```tsx
+
+
+```
+
+스키마 검증이 성공하면 이벤트는 `send` 또는 각 핸들러로 전달됩니다.
+실패하면 `onSchemaError`가 호출되고, `abortOnError`가 true일 경우 이벤트는 무시됩니다.
+
+
+
+## Notes
+
+- Zod 스키마는 기본적으로 [parse](https://zod.dev/?id=parse)를 사용하여 검증됩니다.
+- 부드러운 타입 추론을 위해, createTracker 함수 외부에서 스키마를 정의하고 createTracker의 세 번째 타입 인자에 typeof schemas를 할당하길 권장합니다.
+
+_향후 다른 스키마 검증 라이브러리를 지원할 계획입니다._
diff --git a/docs/src/content/ko/hook.mdx b/docs/src/content/ko/docs/hook.mdx
similarity index 50%
rename from docs/src/content/ko/hook.mdx
rename to docs/src/content/ko/docs/hook.mdx
index c775e8f..09d6258 100644
--- a/docs/src/content/ko/hook.mdx
+++ b/docs/src/content/ko/docs/hook.mdx
@@ -1,31 +1,37 @@
-# hook
+import { Callout } from "nextra/components";
-[`createTracker`](/docs/create-tracker)에서 두 번째 배열 항목으로 반환되는 커스텀 React hook입니다.
-이 훅은 컴포넌트 내에서 이벤트 트래킹 기능과 컨텍스트 관리에 접근할 수 있게 합니다.
+# Hook
+
+React 컴포넌트 내부에서 트래킹 컨텍스트를 설정하거나, 명령형 방식으로 이벤트를 추적할 수 있습니다. 해당 Hook은 [`createTracker`](/docs/create-tracker)에서 반환되는 두 번째 항목입니다.
+
+주로 컴포넌트 마운트 이후, 사용자 입력이나 비동기 작업이 완료된 시점에서 수동으로 이벤트를 트리거할 때 사용됩니다.
```tsx
import { createTracker } from "@offlegacy/event-tracker";
-const [Track, useTracker] = createTracker({...})
+const [Track, useTracker] = createTracker({...});
function MyComponent() {
const { setContext, getContext, track, trackWithSchema } = useTracker();
- return (
- // 컴포넌트 내용
- );
+ // 명령형 이벤트 트래킹
}
```
-### 반환 값
+## Reference
-이 hook은 다음 속성을 포함하는 객체를 반환합니다:
+### Returns
-#### setContext
+| 속성 | 타입 | 설명 |
+| ----------------- | --------------------------------------------------------------- | ------------------------------------------- |
+| `setContext` | `(context: Context \| (prev: Context) => Context) => void` | 트래킹 컨텍스트 설정 또는 업데이트 |
+| `getContext` | `() => Context` | 현재 트래킹 컨텍스트 반환 |
+| `track` | `Record void>` | 일반 이벤트 추적 함수 집합 |
+| `trackWithSchema` | `Record void>` | 스키마 기반 검증 포함 이벤트 추적 함수 집합 |
-- Type: `(context: Context) => void`
-- 현재 트래킹 컨텍스트를 설정하거나 업데이트합니다.
-- 사용자 정보, 세션 데이터 등을 업데이트하는 데 사용할 수 있습니다.
+---
+
+#### `setContext`
```tsx
const { setContext } = useTracker();
@@ -40,11 +46,10 @@ setContext((prev) => ({
}));
```
-#### getContext
+- 현재 트래킹 컨텍스트를 설정하거나 업데이트합니다.
+- 사용자 정보, 세션 데이터 등을 업데이트하는 데 사용할 수 있습니다.
-- Type: `() => Context`
-- 현재 트래킹 컨텍스트를 반환합니다.
-- 현재 트래킹 상태에 접근하는 데 유용합니다.
+#### `getContext`
```tsx
const { getContext } = useTracker();
@@ -53,12 +58,10 @@ const currentContext = getContext();
console.log("Current user:", currentContext.userId);
```
-#### track
+- 현재 트래킹 컨텍스트를 반환합니다.
+- 현재 트래킹 상태에 접근하는 데 유용합니다.
-- Type: `Record void>`
-- 모든 구성된 이벤트 트래킹 함수를 포함하는 객체
-- key는 트래커 구성에 정의된 이벤트 이름과 일치합니다.
-- 고급 제어를 위한 선택적 `TrackingOptions`를 허용합니다.
+#### `track`
```tsx
const { track } = useTracker();
@@ -94,12 +97,11 @@ track.onClick(
track.onImpression({ elementId: "hero" });
```
-#### trackWithSchema
-
-- Type: `Record void>`
-- 스키마 검증이 포함된 모든 구성된 이벤트 트래킹 함수를 포함하는 객체
+- 모든 구성된 이벤트 트래킹 함수를 포함하는 객체
- key는 트래커 구성에 정의된 이벤트 이름과 일치합니다.
-- 고급 제어를 위한 선택적 `TrackingOptions`를 허용합니다.
+- 고급 제어를 위한 선택적 TrackingOptions를 허용합니다.
+
+#### `trackWithSchema`
```tsx
const { trackWithSchema } = useTracker();
@@ -130,39 +132,64 @@ trackWithSchema.onImpression(
);
```
-### TrackingOptions
+- 스키마 검증이 포함된 모든 구성된 이벤트 트래킹 함수를 포함하는 객체
+- key는 트래커 구성에 정의된 이벤트 이름과 일치합니다.
+- 고급 제어를 위한 선택적 TrackingOptions를 허용합니다.
-`track`과 `trackWithSchema` 메서드 모두 다음 옵션을 포함하는 선택적 두 번째 매개변수를 허용합니다:
+## TrackingOptions
-- `enabled?: boolean | ((context: Context, params: EventParams) => boolean)` - 이벤트 추적을 조건부로 활성화/비활성화
-- `debounce?: DebounceConfig` - 연속적인 이벤트 발생을 방지하는 디바운스 설정
-- `throttle?: ThrottleConfig` - 이벤트 발생 빈도를 제한하는 스로틀 설정
+`track`, `trackWithSchema` 함수는 모두 아래 옵션을 선택적으로 받을 수 있습니다:
-**참고:** `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다.
+| 옵션 | 타입 | 설명 |
+| ---------- | ------------------------------------------- | ------------------------------------- |
+| `enabled` | `boolean \| ((context, params) => boolean)` | 조건부로 이벤트 추적 활성화 여부 설정 |
+| `debounce` | `DebounceConfig` | 연속된 이벤트를 제한 (후행 호출 1회) |
+| `throttle` | `ThrottleConfig` | 짧은 시간 내 중복 호출 방지 |
-#### DebounceConfig
+
+ 참고: `debounce`와 `throttle`은 상호 배타적이며 함께 사용할 수 없습니다. 타입 에러를 발생시켜 사전에 방지합니다.
+
-```tsx
+#### `DebounceConfig`
+
+```ts
interface DebounceConfig {
- delay: number; // 밀리초 단위의 지연 시간
- leading?: boolean; // 선행 에지에서 실행 (기본값: false)
- trailing?: boolean; // 후행 에지에서 실행 (기본값: true)
+ delay: number;
+ leading?: boolean; // 기본값: false
+ trailing?: boolean; // 기본값: true
}
```
-#### ThrottleConfig
+#### `ThrottleConfig`
-```tsx
+```ts
interface ThrottleConfig {
- delay: number; // 밀리초 단위의 지연 시간
- leading?: boolean; // 선행 에지에서 실행 (기본값: true)
- trailing?: boolean; // 후행 에지에서 실행 (기본값: false)
+ delay: number;
+ leading?: boolean; // 기본값: true
+ trailing?: boolean; // 기본값: false
}
```
-### 사용 예제
+## Best Practices
+
+### 컨텍스트 관리
+
+- 여러 이벤트에 영향을 주는 전역 상태를 업데이트하기 위해 `setContext`를 사용하세요.
+- 이전 상태에 기반한 업데이트를 위해 `setContext`의 함수 형태를 고려하세요.
+
+### 이벤트 트래킹
+
+- 가능한 경우 `track` 또는 `trackWithSchema`에서 이벤트 함수를 사용하세요.
+
+### 성능 최적화
-다음은 이 hook을 사용하는 예제입니다:
+- 렌더링 중에 이벤트 트래킹 함수를 호출하지 마세요.
+- [배칭](/docs/batching)을 사용하여 성능을 향상시키세요.
+- [데이터 검증](/docs/data-type-validation)을 사용하여 데이터 안전성을 확인하세요.
+
+## Examples
+
+### 기본
```tsx
import { createTracker } from "@offlegacy/event-tracker";
@@ -204,21 +231,3 @@ function UserProfile({ userId }) {
);
}
```
-
-### Best Practices
-
-1. **컨텍스트 업데이트**
-
- - 여러 이벤트에 영향을 주는 전역 상태를 업데이트하기 위해 `setContext`를 사용하세요.
- - 이전 상태에 기반한 업데이트를 위해 `setContext`의 함수 형태를 고려하세요.
-
-2. **이벤트 트래킹**
-
- - 가능한 경우 `track` 또는 `trackWithSchema`에서 이벤트 함수를 사용하세요.
-
-3. **성능**
-
- - 렌더링 중에 이벤트 트래킹 함수를 호출하지 마세요.
- - 콜백 또는 효과를 사용하세요.
- - [배칭](/docs/batching)을 사용하여 성능을 향상시키세요.
- - [데이터 타입 검증](/docs/data-type-validation)을 사용하여 데이터 타입 안전성을 확인하세요.
diff --git a/docs/src/content/ko/docs/installation.mdx b/docs/src/content/ko/docs/installation.mdx
new file mode 100644
index 0000000..85fd943
--- /dev/null
+++ b/docs/src/content/ko/docs/installation.mdx
@@ -0,0 +1,11 @@
+# 설치
+
+Event Tracker는 React 애플리케이션에서 이벤트 트래킹을 쉽게 구현할 수 있도록 설계된 라이브러리입니다. `React@^16.8.0` 이상의 버전에서 사용할 수 있습니다.
+
+최신 안정 버전을 설치하려면 아래 명령어를 실행하세요.
+
+
+
+```shell npm2yarn
+npm install @offlegacy/event-tracker
+```
diff --git a/docs/src/content/ko/docs/introduction.mdx b/docs/src/content/ko/docs/introduction.mdx
new file mode 100644
index 0000000..7517a5b
--- /dev/null
+++ b/docs/src/content/ko/docs/introduction.mdx
@@ -0,0 +1,83 @@
+# 소개
+
+Event Tracker 문서에 오신 것을 환영합니다.
+
+## Event Tracker가 무엇인가요?
+
+Event Tracker는 복잡한 이벤트 트래킹 구현 과정을 단순화하고, 개발자가 비즈니스 로직에 더 집중할 수 있도록 돕는 선언적 방식의 React 라이브러리입니다. 모든 규모의 애플리케이션에서 이벤트 트래킹을 쉽고 효율적으로 관리할 수 있도록 설계되었습니다.
+
+```tsx
+import { createTracker } from "@offlegacy/event-tracker";
+
+// 트래커 인스턴스 생성
+const [Track, useTracker] = createTracker({
+ DOMEvents: {
+ onClick: (params, context) => {
+ log("Click event:", params, context);
+ },
+ },
+});
+
+// 앱에서 사용하기
+function App() {
+ return (
+
+
+
+
+
+ );
+}
+```
+
+### 주요 기능
+
+Event Tracker는 개발자 경험과 애플리케이션 성능을 모두 고려한 다양한 기능을 제공합니다.
+
+| Feature | Description |
+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 선언적 API | 트래킹을 위한 별도의 설정이나 복잡한 코드 없이, 컴포넌트 형태로 직관적으로 선언할 수 있습니다. |
+| 애널리틱스 도구 독립성 | [Google Analytics](https://analytics.google.com/), [Amplitude](https://amplitude.com/) 등 어떤 도구든 자유롭게 연동할 수 있어, 기존 인프라를 변경하지 않고도 도입이 가능합니다. |
+| 명확한 관심사 분리 | 트래킹 로직을 비즈니스 코드에서 완전히 분리함으로써 코드의 가독성, 테스트 용이성, 유지보수성을 모두 향상시킵니다. |
+| 최적화된 성능 | 배칭, 디바운스, 스로틀링 등 네트워크 요청을 최소화하는 다양한 전략이 내장되어 있어, 성능 저하 없이 안정적으로 트래킹할 수 있습니다. |
+| 실행 순서 보장 | 비동기 상황에서도 이벤트가 의도한 순서대로 처리되도록 설계되어, 복잡한 사용자 흐름에서도 정확한 트래킹이 가능합니다. |
+| 데이터 검증 | [Zod](https://zod.dev/) 기반의 정적 스키마 검증으로 빌드 타임에서 오류를 방지하고, 수집되는 이벤트 데이터의 신뢰도를 보장합니다. |
+
+## 핵심 개념
+
+Event Tracker를 효과적으로 사용하기 위해 알아야 할 몇 가지 핵심 개념이 있습니다.
+
+### 인스턴스 (`createTracker`)
+
+라이브러리의 가장 기본적인 출발점입니다. `createTracker` 함수를 사용하여 트래커 인스턴스(`Track` 컴포넌트 컬렉션과 `useTracker` 훅)를 생성합니다. 이때, DOM 이벤트 핸들러, 노출(Impression) 이벤트 핸들러, 스키마 등을 설정하여 이벤트 트래킹을 정의합니다.
+
+목적에 따라 구분하여 여러 가지 트래커 인스턴스를 생성할 수 있습니다. (예를 들어, Google Analytics로 보내는 이벤트와 Amplitude로 보내는 이벤트를 구분하여 생성할 수 있습니다.)
+
+### 프로바이더 (`Track.Provider`)
+
+React의 Context API를 기반으로 구현되었습니다. 애플리케이션 또는 특정 컴포넌트 트리의 최상단에서 `Track.Provider`로 감싸 하위 컴포넌트들에 트래킹에 필요한 공통 데이터(컨텍스트)를 제공합니다. 예를 들어, `userId`, `pageName` 등의 정보를 컨텍스트로 전달하면, 각 이벤트 트래킹 시 이 정보를 활용할 수 있습니다.
+
+### 이벤트 컴포넌트 (`Track.Click`, `Track.PageView` 등)
+
+선언적으로 이벤트를 트래킹할 수 있도록 제공되는 특수 컴포넌트들입니다. `createTracker` 리턴 배열의 첫 번째 요소입니다.
+
+- `Track.Click`: 자식 요소에서 클릭 이벤트가 발생했을 때 트래킹합니다.
+- `Track.Impression`: 자식 요소가 화면에 노출되었을 때 트래킹합니다.
+- `Track.PageView`: 컴포넌트가 마운트될 때 페이지 뷰 이벤트를 트래킹합니다.
+
+이 외에도 다양한 사용자 인터랙션 및 생명주기 이벤트에 대응하는 컴포넌트를 제공하거나 커스텀하여 사용할 수 있습니다. 각 컴포넌트는 `context`, `params` prop을 통해 해당 이벤트와 관련된 특정 데이터를 전달받고 활용할 수 있습니다.
+
+### 커스텀 훅
+
+컴포넌트의 생명주기나 DOM 이벤트와 직접적으로 관련되지 않은, 보다 복잡하거나 조건부적인 이벤트 트래킹이 필요할 때 사용합니다. 훅을 사용하면 `Track.Provider`로부터 컨텍스트 정보를 가져오고, 정의된 트래킹 로직을 명령형으로 사용할 수 있습니다.
+
+## 다음 단계
+
+이러한 핵심 개념들은 서로 유기적으로 작동하여 Event Tracker의 강력하고 유연한 이벤트 트래킹 환경을 구성합니다. 더 자세한 사용법과 각 기능에 대한 심층적인 내용은 아래 문서들에서 확인하실 수 있습니다.
+
+- [왜 Event Tracker인가요?](/docs/why-event-tracker): Event Tracker의 필요성과 주요 기능 알아보기
+- [`createTracker`](/docs/create-tracker): 트래커 인스턴스 생성 및 설정 방법 알아보기
+- [Components](/docs/components): 사용 가능한 모든 트래킹 컴포넌트와 사용 예시 살펴보기
+- [Hook](/docs/hook): 커스텀 훅을 활용한 사용자 지정 트래킹 방법 알아보기
+- [배칭](/docs/batching): 이벤트 배칭을 통한 성능 최적화 전략 알아보기
+- [데이터 검증](/docs/data-type-validation): Zod 스키마를 활용한 데이터 유효성 검증하기
diff --git a/docs/src/content/ko/docs/why-event-tracker.mdx b/docs/src/content/ko/docs/why-event-tracker.mdx
new file mode 100644
index 0000000..5a504aa
--- /dev/null
+++ b/docs/src/content/ko/docs/why-event-tracker.mdx
@@ -0,0 +1,198 @@
+import { Steps } from "nextra/components";
+
+# 왜 Event Tracker인가요?
+
+현대 웹 애플리케이션은 사용자의 행동을 분석하여 서비스 품질을 지속적으로 개선해야 합니다. 그러나 기존의 이벤트 트래킹 방식은 여러 문제점이 나타납니다.
+
+## Event Tracker가 필요한 이유
+
+다음은 전통적인 이벤트 트래킹 방식의 문제점을 보여주는 예시입니다.
+
+```tsx {8,15, 24-31}
+function Page() {
+ const { user, userId } = useUser(); // 사용자 정보와 ID를 가져옵니다.
+
+ return (
+
+
User: {user.name}
+ {/* Counter 컴포넌트에 이벤트 트래킹을 위해 userId를 전달합니다. */}
+
+
+ );
+}
+
+// 오직 이벤트 트래킹만을 위해서 'userId'를 prop으로 전달받습니다.
+// 만약 Counter가 더 깊은 곳에 있다면, prop drilling은 더욱 심해집니다.
+function Counter({ userId }: { userId: string }) {
+ const [count, setCount] = useState(0);
+ const { track } = useTrackEvent(); // 가상의 트래킹 훅
+
+ const handleIncrement = () => {
+ const newCount = count + 1;
+ setCount(newCount);
+
+ // 비즈니스 로직 (카운트 증가)과 트래킹 로직이 혼재합니다.
+ track({
+ event: "click_increment",
+ params: {
+ type: "count",
+ value: newCount,
+ userId, // 상위로부터 전달받은 userId 사용
+ },
+ });
+ };
+
+ return (
+
+
Count: {count}
+
+
+ );
+}
+```
+
+
+
+### Prop Drilling의 고통
+
+이벤트 트래킹에 필요한 데이터를 하위 컴포넌트까지 전달하기 위해 수많은 계층을 거쳐 prop을 내려보내야 하는 경우가 많습니다. 이는 코드의 가독성을 해치고 유지보수를 어렵게 만듭니다.
+
+### 로직의 강한 결합
+
+비즈니스 로직과 이벤트 트래킹 로직이 한데 섞여 코드의 복잡도를 높이고, 각 로직의 독립적인 테스트와 수정을 어렵게 만듭니다.
+
+### 보일러플레이트 코드 증가
+
+반복적인 트래킹 코드 작성은 개발 생산성을 저해하는 요인이 됩니다.
+
+
+
+## Event Tracker가 제시하는 새로운 패러다임
+
+Event Tracker는 이벤트 트래킹을 위한 새로운 패러다임을 소개합니다.
+Event Tracker가 제시하는 선언적 방식은 전통적으로 이벤트 트래킹과 관련된 복잡성을 단순화하여, 모든 개발자들이 쉽게 접근할 수 있도록 합니다.
+
+
+
+### 선언적 이벤트 트래킹
+
+```tsx {7, 10, 12, 32, 34}
+function Page() {
+ const { user, userId } = useUser();
+
+ // Track.Provider를 통해 하위 컴포넌트에 트래킹 컨텍스트(userId)를 제공합니다.
+ // 더 이상 prop drilling이 필요 없습니다.
+ return (
+
+
- );
-};
-```
-
-위 코드로 알아본 이벤트 트래킹으로 인한 두 가지 주요 불편사항은 다음과 같습니다:
-
-1. **Prop Drilling**: `userId`가 `` 컴포넌트에서 `` 컴포넌트로 prop으로 전달됩니다. `` 컴포넌트가 컴포넌트 트리 깊숙이 중첩되어 있다면, prop drilling이 더 심각해져 코드의 가독성과 유지보수성이 저하될 수 있습니다.
-2. **이벤트 트래킹 로직과 비즈니스 로직의 강결합**: `handleIncrement` 함수는 카운트 증가 로직과 이벤트 트래킹 로직을 모두 포함하고 있습니다. 이벤트 트래킹 로직을 분리하면 코드를 더 깔끔하고 유지보수하기 쉽게 만들 수 있습니다.
-
-## `event-tracker`가 제시하는 새로운 패러다임
-
-`event-tracker`는 이벤트 트래킹을 위한 새로운 패러다임을 소개합니다.
-`event-tracker`가 제시하는 선언적 방식은 전통적으로 이벤트 트래킹과 관련된 복잡성을 단순화하여,
-모든 개발자들이 쉽게 접근할 수 있도록 합니다.
-
-### 선언적 이벤트 트래킹
-
-```tsx {5, 10, 24, 26}
-const Page = () => {
- const { user, userId } = useUser();
-
- return (
-
-