useFlag.ts72 lines · main
1import * as Sentry from '@sentry/nextjs'
2import { IS_PLATFORM, useFeatureFlags } from 'common'
3
4import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
5import { trackFeatureFlag } from '@/lib/posthog'
6
7const isObjectEmpty = (obj: Object) => {
8 return Object.keys(obj).length === 0
9}
10
11/**
12 * Hook to retrieve a PostHog feature flag value.
13 *
14 * @returns `undefined | false | T` where:
15 * - `undefined` = PostHog store is still loading OR flag doesn't exist (treat as "don't show")
16 * - `false` = Flag is explicitly set to false (typically means "disabled" or "control" for experiments)
17 * - `T` = The actual flag value (string, boolean, or custom type like variant names)
18 *
19 * @example Experiment usage convention:
20 * ```typescript
21 * const variant = usePHFlag<ExperimentVariant | false>('experimentName')
22 *
23 * // undefined = loading/doesn't exist, don't render anything yet
24 * if (variant === undefined) return null
25 *
26 * // false = explicitly disabled, show control
27 * if (variant === false) return <Control />
28 *
29 * // Otherwise, variant has a value, show experiment
30 * return <Experiment variant={variant} />
31 * ```
32 *
33 * @todo TODO(Alaister): move this to packages/common/feature-flags.tsx and rename to useFlag
34 * @todo TODO(sean): Refactor to have explicit loading/disabled/value states
35 * See https://linear.app/briven/issue/GROWTH-539
36 */
37export function usePHFlag<T = string | boolean>(name: string) {
38 const flagStore = useFeatureFlags()
39 // [Joshen] Prepend PH flags with "PH" in local storage for easier identification of PH flags
40 const [trackedValue, setTrackedValue] = useLocalStorageQuery(`ph_${name}`, '')
41
42 const store = flagStore.posthog
43 const flagValue = store[name]
44
45 if (!IS_PLATFORM) return false
46
47 // Flag store has not been initialized
48 if (isObjectEmpty(store)) return undefined
49
50 if (!isObjectEmpty(store) && flagValue === undefined) {
51 console.error(`Flag key "${name}" does not exist in PostHog flag store`)
52 return undefined
53 }
54
55 if (trackedValue !== flagValue) {
56 try {
57 // [Joshen] Only fire the track endpoint once across sessions unless the flag value changes
58 // Note: This cannot guarantee excess calls in the event for e.g user clears local storage or uses incognito
59 // trackFeatureFlag checks for telemetry consent before actually firing the request too
60 trackFeatureFlag({ feature_flag_name: name, feature_flag_value: flagValue })
61 setTrackedValue(flagValue as string)
62 } catch (error: any) {
63 Sentry.withScope((scope) => {
64 scope.setTag('type', 'phTrackFailure')
65 Sentry.captureException(error)
66 })
67 console.error(error.message)
68 }
69 }
70
71 return flagValue as T
72}