Blog>
Snippets

Updating Chart Data using Context and Hooks

Illustrate the use of useContext and useState hooks for updating chart data globally stored in React Context, triggered by a user action.
import React, { useContext, useState } from 'react';

const ChartContext = React.createContext();
First, we define our ChartContext using React's createContext, allowing us to use this context later to store and provide chart data globally.
const ChartProvider = ({ children }) => {
  const [chartData, setChartData] = useState([]);
  
  const updateChartData = (newData) => {
    setChartData(newData);
  };
  
  return (
    <ChartContext.Provider value={{ chartData, updateChartData }}>
      {children}
    </ChartContext.Provider>
  );
};
Define a ChartProvider component that includes a state for chartData and a method to update it. This provider wraps child components, allowing them to access chartData and the method to update it via context.
const Chart = () => {
  const { chartData, updateChartData } = useContext(ChartContext);
  
  const fetchDataAndUpdateChart = async () => {
    // Assume fetchChartData is a function that fetches chart data
    const newData = await fetchChartData();
    updateChartData(newData);
  };
  
  return (
    <div>
      {/* Render your chart using chartData here */}
      <button onClick={fetchDataAndUpdateChart}>Update Chart</button>
    </div>
  );
};
The Chart component, which is a consumer of the ChartContext. It uses the useContext hook to access the global chartData and the method to update it. A button is provided to trigger a fetch and update operation on the chart data.