1+ /*
2+ * Microsoft Clarity React Context Provider
3+ *
4+ * This provider injects the Microsoft Clarity analytics script into your app and exposes
5+ * the Clarity API via React context. Use the `useClarity` hook to access the Clarity function
6+ * anywhere in your component tree.
7+ *
8+ * Usage:
9+ * import { useClarity } from './ClarityProvider';
10+ * const clarity = useClarity();
11+ * clarity('set', 'userId', '123'); // Example Clarity API call
12+ *
13+ * The Clarity project ID is read from VITE_REACT_APP_CLARITY_PROJECT_ID in your environment.
14+ */
115import React , { useEffect , createContext , useContext , useCallback } from 'react' ;
216
17+ // Extend the Window interface to include the Clarity function
318declare global {
419 interface Window {
520 clarity ?: ( ...args : any [ ] ) => void ;
621 }
722}
823
24+ // Your Microsoft Clarity project ID is read from VITE_REACT_APP_CLARITY_PROJECT_ID
925const CLARITY_PROJECT_ID = import . meta. env . VITE_REACT_APP_CLARITY_PROJECT_ID as string ;
26+
27+ // Type for the Clarity function
1028type ClarityFn = ( ...args : any [ ] ) => void ;
29+
30+ // Create the Clarity context
1131export const ClarityContext = createContext < ClarityFn | undefined > ( undefined ) ;
1232
33+ /**
34+ * useClarity hook
35+ *
36+ * Returns the Clarity function from context. Use this to call Clarity API methods.
37+ * Example: const clarity = useClarity();
38+ */
1339export const useClarity = ( ) => useContext ( ClarityContext ) ;
1440
41+ /**
42+ * ClarityProvider component
43+ *
44+ * Injects the Clarity script on mount and provides the Clarity function via context.
45+ * Wrap your app with this provider (typically in AppMain.tsx).
46+ */
1547const ClarityProvider : React . FC < { children : React . ReactNode } > = ( { children } ) => {
1648 useEffect ( ( ) => {
49+ // Inject the Clarity script only once, if not already present
1750 if ( typeof window !== 'undefined' && ! window . clarity ) {
1851 ( function ( c : any , l : Document , a : string , r : string , i : string ) {
1952 c [ a ] =
@@ -32,6 +65,7 @@ const ClarityProvider: React.FC<{ children: React.ReactNode }> = ({ children })
3265 }
3366 } , [ ] ) ;
3467
68+ // Memoized clarity function that calls window.clarity if available
3569 const clarity = useCallback < ClarityFn > ( ( ...args ) => {
3670 if ( typeof window !== 'undefined' && typeof window . clarity === 'function' ) {
3771 window . clarity ( ...args ) ;
0 commit comments