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` (`createContext<ChartContextProps | null>(null)`); `<ChartContainer>` provides `{ config }` (ChartConfig). Chart sub-components (ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent) rendered outside `<ChartContainer>` throw so config-driven rendering never reads null.

Source

Thrown at apps/v4/registry/bases/aria/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 subtree (including `<ChartTooltip>`/`<ChartLegend>`) in `<ChartContainer config={chartConfig}>`.
  2. Pass a valid `config` prop to ChartContainer (it is required).
  3. Decorate tests/stories with `<ChartContainer>`.

Example fix

// before
<ChartTooltipContent />
<ChartContainer config={cfg}>...</ChartContainer>

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

Strategy: type-guard

Validate before calling

render(<ChartContainer config={cfg}><ChartTooltip><ChartTooltipContent/></ChartTooltip></ChartContainer>)

Type guard

import React from "react"
import { ChartContext } from "@/registry/bases/aria/ui/chart"
const insideChart = () => React.useContext(ChartContext) != null

Try / catch

try { useChart() } catch (e) { if (e.message.includes("<ChartContainer />")) {/*wrap in ChartContainer*/} throw e }

Prevention

When it happens

Trigger: Mounting chart helpers (e.g. `<ChartTooltip />`, `<ChartLegendContent />`) outside `<ChartContainer config={...}>`. Typically when porting a chart from the docs and dropping or relocating the container.

Common situations: Building a custom chart layout where the tooltip is rendered as a sibling of ChartContainer; reusing tooltip content in a non-chart context; tests of individual parts.

Related errors


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