Add useAnalytics hook with server-safe NoopAnalytics fallback
This commit is contained in:
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user