shadcn-ui/ui · error · Error

useChart must be used within a <ChartContainer />

Error message

useChart must be used within a <ChartContainer />

What it means

Same guard as the bases/radix chart: useChart reads ChartContext, populated only by <ChartContainer>. This is the new-york-v4 legacy copy; any chart sub-component (ChartTooltipContent, ChartLegendContent) calling useChart outside <ChartContainer> throws.

Source

Thrown at apps/v4/registry/new-york-v4/ui/chart.tsx:36

    label?: React.ReactNode
    icon?: React.ComponentType
  } & (
    | { color?: string; theme?: never }
    | { color?: never; theme: Record<keyof typeof THEMES, string> }
  )
>

type ChartContextProps = {
  config: ChartConfig
}

const ChartContext = React.createContext<ChartContextProps | null>(null)

function useChart() {
  const context = React.useContext(ChartContext)

  if (!context) {
    throw new Error("useChart must be used within a <ChartContainer />")
  }

  return context
}

function ChartContainer({
  id,
  className,
  children,
  config,
  initialDimension = INITIAL_DIMENSION,
  ...props
}: React.ComponentProps<"div"> & {
  config: ChartConfig
  children: React.ComponentProps<
    typeof RechartsPrimitive.ResponsiveContainer
  >["children"]
  initialDimension?: {

View on GitHub (pinned to efac598707)

Solutions

  1. Wrap the chart in <ChartContainer config={config}>.
  2. Keep ChartTooltip/ChartLegend inside the ChartContainer tree.
  3. Reuse the same config object for container and tooltip.

Example fix

// before
<BarChart>
  <ChartTooltip content={<ChartTooltipContent />} />
</BarChart>

// after
<ChartContainer config={config}>
  <BarChart>
    <ChartTooltip content={<ChartTooltipContent />} />
  </BarChart>
</ChartContainer>
Defensive patterns

Strategy: validation

Validate before calling

function useOptionalChart() {
  return React.useContext(ChartContext)
}
const chart = useOptionalChart()
if (!chart) return null

Type guard

function useHasChartContainer(): boolean {
  return React.useContext(ChartContext) !== null
}

Prevention

When it happens

Trigger: Using new-york-v4 chart sub-components on a raw Recharts chart without <ChartContainer>; rendering ChartTooltip/ChartLegend in isolation.

Common situations: Migrating a chart off the new-york-v4 style; Storybook stories rendering chart pieces without the container.

Related errors


AI-assisted analysis of shadcn-ui/ui@efac598707 (2026-08-12). Data as JSON: /api/errors/e111fd4d462bc9a0. Report an issue: GitHub.