Blog>
Snippets

Building a Custom Hook for Fetching and Caching Chart Data

Provide an example of creating a custom React hook that fetches chart data from an API, caches it, and integrates with React Context for global state management.
import { useState, useEffect, useContext, createContext } from 'react';

const ChartDataContext = createContext();

export const useChartDataContext = () => useContext(ChartDataContext);
This code creates a context for storing chart data, making it accessible throughout your component tree without prop drilling.
export const useFetchChartData = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const result = await response.json();
        setData(result);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    const dataFromCache = sessionStorage.getItem(url);
    if (dataFromCache) {
      setData(JSON.parse(dataFromCache));
      setLoading(false);
    } else {
      fetchData();
    }
  }, [url]);

  useEffect(() => {
    if (data) {
      sessionStorage.setItem(url, JSON.stringify(data));
    }
  }, [data, url]);

  return { loading, data, error };
};
This custom hook fetches chart data from the given URL. It checks for cached data in the session storage to minimize network requests. If no cached data is found, it fetches from the API and caches the new data.
export const ChartDataProvider = ({ children }) => {
  const chartData = useFetchChartData('Your-API-URL');

  return (
    <ChartDataContext.Provider value={chartData}>
      {children}
    </ChartDataContext.Provider>
  );
};
This provider component uses the custom hook to fetch chart data and provides it to all child components via the React Context created earlier.