Blog>
Snippets

Custom Hook for Dynamic Data Fetching with React Charts

Showcase creating a custom hook that fetches data dynamically based on user interaction or chart state, displaying new data without reloading.
import { useState, useEffect } from 'react';

const useDynamicChartData = (dataEndpoint) => {
  const [chartData, setChartData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(dataEndpoint);
      const data = await response.json();
      setChartData(data);
    };

    fetchData();
  }, [dataEndpoint]);

  return chartData;
};
Defines a custom hook named useDynamicChartData that takes a data endpoint URL as an argument. It uses the useState hook to manage the chart data state and the useEffect hook to fetch data from the provided endpoint whenever the endpoint changes. The fetched data is then stored in the chartData state, making it available for use in a chart component.
import React from 'react';
import { useDynamicChartData } from './useDynamicChartData';
import { Chart } from 'tanstack-react-charts';

const DynamicChartComponent = ({ dataEndpoint }) => {
  const data = useDynamicChartData(dataEndpoint);

  return (
    <Chart
      options={{
        data,
        type: 'bar',
        // additional chart options
      }}
    />
  );
};
Implements a React component that utilizes the custom hook useDynamicChartData to fetch data dynamically based on a provided endpoint. The fetched data is passed as a prop to the TanStack React Chart component to render a chart. This example demonstrates how the chart data can be updated dynamically without reloading the page, based on the dataEndpoint prop.