Blog>
Snippets

Managing State with Context in TanStack React Charts

Illustrate how to use the React Context API to manage and distribute chart state across deeply nested chart components.
import React, { createContext, useContext, useState } from 'react';

const ChartContext = createContext();
Creates a ChartContext using React's createContext API, which will be used to pass down chart state and settings throughout the component tree.
const ChartProvider = ({ children }) => {
  const [chartData, setChartData] = useState(null);
  const value = { chartData, setChartData };

  return (
    <ChartContext.Provider value={value}>
      {children}
    </ChartContext.Provider>
  );
};
Defines a ChartProvider component that uses the Context.Provider to pass down chart data and a method to update it. Any child components can access this data and the setter function.
const useChart = () => {
  const context = useContext(ChartContext);
  if (!context) {
    throw new Error('useChart must be used within a ChartProvider');
  }
  return context;
};
Implements a custom hook named useChart to make it easier to access the chart context from any component. This ensures that the component is wrapped with a ChartProvider.
// Example of a component using the useChart hook
class Chart extends React.Component {
  render() {
    const { chartData } = useChart();
    // Chart rendering logic using chartData
    return <div>/* Rendered Chart */</div>;
  }
}
Shows how to use the useChart hook within a functional React component to access chartData. A class component example is shown for context, but React's useContext hook is typically used in functional components.