useChart Hook

Access chart state and context for building custom chart components

Overview

The useChart hook provides access to the chart's internal state, scales, dimensions, and tooltip data. Use it to build custom components that integrate with the chart system.

import { useChart } from "@bklitui/ui/charts";

function MyCustomComponent() {
  const { tooltipData, hoveredBarIndex, yScale, innerHeight } = useChart();
  // ... use chart state
}

Requirements

The hook must be used within a chart component (LineChart, AreaChart, or BarChart). It will throw an error if used outside of a chart context.

// Correct: Inside a chart
<BarChart data={data} xDataKey="month">
  <MyCustomComponent /> {/* useChart works here */}
</BarChart>

// Error: Outside a chart
<MyCustomComponent /> {/* useChart will throw */}

Return Values

Dimensions

PropertyTypeDescription
widthnumberTotal chart width in pixels
heightnumberTotal chart height in pixels
innerWidthnumberChart area width (excluding margins)
innerHeightnumberChart area height (excluding margins)
marginMarginChart margins { top, right, bottom, left }
columnWidthnumberWidth of a single data column

Scales

PropertyTypeDescription
xScaleScaleTimeTime scale for x-axis (line/area charts)
yScaleScaleLinearLinear scale for y-axis values
barScaleScaleBand | undefinedBand scale for categorical x-axis (bar charts only)
bandWidthnumber | undefinedWidth of each bar band (bar charts only)

Tooltip State

PropertyTypeDescription
tooltipDataTooltipData | nullCurrent tooltip data when hovering
setTooltipDataDispatchSetter for tooltip data
hoveredBarIndexnumber | null | undefinedIndex of hovered bar (bar charts only)
setHoveredBarIndexFunction | undefinedSetter for hovered bar index

TooltipData Structure

interface TooltipData {
  point: Record<string, unknown>;  // The data point being hovered
  index: number;                    // Index in the data array
  x: number;                        // X position in pixels
  yPositions: Record<string, number>;  // Y positions keyed by dataKey
  xPositions?: Record<string, number>; // X positions (grouped bars)
}

Container & Animation

PropertyTypeDescription
containerRefRefObject<HTMLDivElement>Ref to chart container (for portals)
isLoadedbooleanWhether chart has finished initial animation
animationDurationnumberAnimation duration in milliseconds

Data & Configuration

PropertyTypeDescription
dataRecord<string, unknown>[]The chart's data array
linesLineConfig[]Registered line/bar configurations
xAccessorFunctionFunction to get Date from data point
barXAccessorFunction | undefinedFunction to get category string (bar charts)
dateLabelsstring[]Pre-computed date labels for ticker

Bar Chart Specific

PropertyTypeDescription
orientation"vertical" | "horizontal"Bar chart orientation
stackedboolean | undefinedWhether bars are stacked
stackOffsetsMapStack offset values for stacked bars

Common Use Cases

Reading Hover Position

function HoverIndicator() {
  const { tooltipData, innerHeight, margin } = useChart();
  
  if (!tooltipData) return null;
  
  return (
    <div 
      style={{ 
        position: 'absolute',
        left: tooltipData.x + margin.left,
        top: margin.top,
        height: innerHeight,
      }}
    >
      {/* Custom indicator */}
    </div>
  );
}

Accessing Bar Positions

function BarOverlay() {
  const { barScale, bandWidth, hoveredBarIndex, data } = useChart();
  
  if (!barScale || hoveredBarIndex === null) return null;
  
  const hoveredData = data[hoveredBarIndex];
  const x = barScale(hoveredData.category);
  
  return (
    <rect x={x} width={bandWidth} /* ... */ />
  );
}

Using Scales for Custom Rendering

function CustomMarker({ value, category }) {
  const { yScale, barScale, innerHeight } = useChart();
  
  const y = yScale(value);
  const x = barScale?.(category) ?? 0;
  
  return (
    <circle cx={x} cy={y} r={5} fill="red" />
  );
}