Add useAnalytics hook with server-safe NoopAnalytics fallback

This commit is contained in:
2026-04-15 00:15:43 +03:00
parent 8878dcb6c8
commit 6a4be07911
+23
View File
@@ -0,0 +1,23 @@
import { createContext, useContext } from "react";
import type { Analytics } from "./types.js";
const NOOP_ANALYTICS: Analytics = {
track() {},
page() {},
};
/**
* React context for the Analytics instance.
* Exported for use by AnalyticsLoader (which sets the provider value).
*/
export const AnalyticsContext = createContext<Analytics | null>(null);
/**
* Returns the Analytics instance from context.
* Server-side and before AnalyticsLoader initializes: returns NoopAnalytics.
* Client-side after init: returns the real facade instance.
*/
export function useAnalytics(): Analytics {
const analytics = useContext(AnalyticsContext);
return analytics ?? NOOP_ANALYTICS;
}