shadcn-ui/ui · error · Error

useChart must be used within a <ChartContainer />

Error message

useChart must be used within a <ChartContainer />

What it means

Identical contract to [152] but in the `base` style registry. `useChart` reads `ChartContext`; chart parts rendered outside `<ChartContainer>` throw so config is never null.

Source

Thrown at apps/v4/registry/bases/base/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 chart parts in `<ChartContainer config={cfg}>` from the `base` style import path.
  2. Always pass a `config` prop to ChartContainer.
  3. Decorate tests/stories with `<ChartContainer>`.

Example fix

// before
<ChartTooltip />
<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>) // base style imports

Type guard

import React from "react"
import { ChartContext } from "@/registry/bases/base/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 `<ChartTooltipContent />` / `<ChartLegendContent />` outside `<ChartContainer config={...}>` when importing from the `base` style.

Common situations: Using the `base` style and relocating tooltip/legend outside the container; tests of individual parts.

Related errors


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