Skip to content

useFeatureFlag throws "Cannot read properties of undefined (reading 'enabled')" when FeatureFlagContext is undefined #8114

Description

@lumaxis

Description

useFeatureFlag calls context.enabled(flag) without guarding against an undefined context. In rare cases the FeatureFlagContext value resolves to undefined at call time -- for example when a duplicate or partially-initialized copy of @primer/react ends up in the bundle graph, so the imported FeatureFlagContext binding is undefined and useContext(undefined) returns undefined. The hook then throws an uncaught TypeError: Cannot read properties of undefined (reading 'enabled').

Because ThemeProvider calls useFeatureFlag('primer_react_theme_provider_remove_ssr_handoff') during render, this can crash any tree that renders a ThemeProvider. Since the throw originates inside Primer (above the app's own providers), application error boundaries placed inside the provider tree do not catch it.

Affected version

@primer/react 38.30.0 (the code is unchanged on main).

Source

packages/react/src/FeatureFlags/useFeatureFlag.ts:

export function useFeatureFlag(flag: string): boolean {
  const context = useContext(FeatureFlagContext)
  return context.enabled(flag) // throws if `context` is undefined
}

Suggested fix

Guard against an undefined context so a degraded module-loading state can't crash rendering, while preserving the existing "unknown flag -> false" contract:

export function useFeatureFlag(flag: string): boolean {
  const context = useContext(FeatureFlagContext)
  return context?.enabled(flag) ?? false
}

(Alternatively, fall back to DefaultFeatureFlags when the context is missing.)

Impact

Low frequency but user-facing: an uncaught render error that can take down a subtree using ThemeProvider.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions