@probat/react 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ "use client";
2
+
3
+ import React, { createContext, useContext, type ReactNode } from "react";
4
+
5
+ /**
6
+ * Factory that creates a typed context + hook pair for passing a variantKey
7
+ * between components in different files without prop-drilling.
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * // experiment-context.ts
12
+ * export const { ExperimentProvider, useVariantKey } = createExperimentContext("pricing-test");
13
+ *
14
+ * // Parent.tsx
15
+ * const { variantKey } = useExperiment("pricing-test");
16
+ * <ExperimentProvider value={variantKey}><Child /></ExperimentProvider>
17
+ *
18
+ * // Child.tsx (different file)
19
+ * const variantKey = useVariantKey();
20
+ * const trackRef = useTrack({ experimentId: "pricing-test", variantKey });
21
+ * ```
22
+ */
23
+ export function createExperimentContext(experimentId: string) {
24
+ const Ctx = createContext<string | null>(null);
25
+
26
+ function ExperimentProvider({
27
+ value,
28
+ children,
29
+ }: {
30
+ value: string;
31
+ children: ReactNode;
32
+ }) {
33
+ return React.createElement(Ctx.Provider, { value }, children);
34
+ }
35
+
36
+ function useVariantKey(): string {
37
+ const v = useContext(Ctx);
38
+ if (v === null) {
39
+ throw new Error(
40
+ `useVariantKey() must be used inside <ExperimentProvider> for "${experimentId}"`
41
+ );
42
+ }
43
+ return v;
44
+ }
45
+
46
+ return { ExperimentProvider, useVariantKey };
47
+ }