Blog>
Snippets

Creating a Global State with React Context for Chart Data

Showcase how to create a React Context for managing global state of chart data, including the Context provider and consumer components.
import React, { createContext, useState, useContext } from 'react';

const ChartDataContext = createContext();

export const ChartDataProvider = ({ children }) => {
  const [chartData, setChartData] = useState([]);

  // Function to update the chart data
  const updateChartData = (newData) => {
    setChartData(newData);
  };

  return (
    <ChartDataContext.Provider value={{ chartData, updateChartData }}>
      {children}
    </ChartDataContext.Provider>
  );
};
This code snippet creates a React Context specifically for managing global state of chart data, including a provider component that allows any child components to access and modify the chart data.
import React from 'react';
import { useContext } from 'react';
import { ChartDataContext } from './ChartDataProvider';

const ChartConsumerComponent = () => {
  const { chartData, updateChartData } = useContext(ChartDataContext);

  // Example function that could update chart data
  const changeChartData = () => {
    const newData = [...chartData, Math.random()]; // Simplified new data generation
    updateChartData(newData);
  };

  return (
    <div>
      <button onClick={changeChartData}>Update Chart Data</button>
    </div>
  );
};
This component demonstrates how to consume the global chart data context within a child component, enabling it to access and modify the chart data using the context provided functions.