shadcn-ui/ui · error · Error

useChart must be used within a <ChartContainer />

Error message

useChart must be used within a <ChartContainer />

What it means

useChart reads ChartContext, which is only populated by <ChartContainer> (it renders <ChartContext.Provider value={{ config }}>). Any chart sub-part that needs the config (ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent) calls useChart; without a <ChartContainer> ancestor the context is null and the hook throws, since rendering a tooltip/legend without a config is meaningless.

Source

Thrown at apps/v4/registry/bases/radix/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 Recharts chart and its sub-components in <ChartContainer config={config}>.
  2. Ensure the same config object passed to ChartContainer is the one the tooltip/legend reads.
  3. Move ChartTooltip/ChartLegend back inside the <ChartContainer> tree.

Example fix

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

// 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 <ChartTooltipContent> or <ChartLegend> on a raw Recharts chart that is not wrapped in <ChartContainer>; splitting a chart into pieces and rendering the legend elsewhere; forgetting ChartContainer when migrating from plain Recharts.

Common situations: Copy-pasting only the <ChartTooltip> from an example; rendering chart pieces in Storybook without the container; refactor that swaps ChartContainer for a div.

Related errors


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