Overview
TheuseChartTooltip hook provides tooltip functionality for SVG-based charts. It tracks mouse position, calculates the nearest data point, and manages tooltip visibility state. The hook is used across performance charts to display formatted values on hover.
Import
Signature
Parameters
Array of numeric data values to display in the tooltip. Represents the y-values of your chart data.
Function to format the tooltip value for display. Receives the raw data point value and should return a formatted string.Common formatters:
formatPrice- For currency values (e.g., “$42,123.45”)formatCompactCurrency- For abbreviated values (e.g., “$1.2M”)- Custom formatting functions
Return Value
Returns an object with tooltip state and event handlers:Tooltip state object containing:
visible(boolean): Whether the tooltip should be displayedx(number): X-coordinate in pixels relative to SVG elementy(number): Y-coordinate in pixels relative to SVG elementvalue(string|number): Formatted value to displayindex(number|null): Index of the data point in the dataPoints array
React ref to attach to the SVG element. Required for calculating mouse position.
Event handler for mouse move events. Attach to the SVG element’s
onMouseMove prop.Calculates the nearest data point based on mouse position and updates tooltip state.Event handler for mouse leave events. Attach to the SVG element’s
onMouseLeave prop.Hides the tooltip when the mouse leaves the chart area.Usage Example
Basic Chart with Tooltip
MainPerformanceChart.jsx:1-7
Portfolio Performance Chart
Custom Value Formatter
Implementation Details
Position Calculation
The hook calculates the tooltip position by:- Getting the SVG element’s bounding rectangle
- Converting mouse coordinates to relative position (0-1 range)
- Mapping the relative position to the nearest data point index
- Clamping the index to valid array bounds
Performance Optimization
- Uses
useCallbackto memoize event handlers, preventing unnecessary re-renders - Dependencies are properly declared for
dataPointsandformatValue - Efficient calculation with minimal DOM queries
Coordinate System
x: Horizontal position in pixels from the left edge of the SVGy: Fixed at half the SVG height (vertical center)index: Integer index into thedataPointsarray
Common Use Cases
- Price Charts: Display formatted cryptocurrency prices on hover
- Performance Charts: Show portfolio value at specific time points
- Trend Analysis: Examine precise values in sparkline charts
- Comparison Charts: Compare values across multiple data series
Related Hooks
- useDashboardData - Provides chart data for the main performance chart
- useTranslations - Used in chart components for labels
Source Location
/workspace/source/src/hooks/useChartTooltip.js:9