Blog>
Snippets

Implementing a Custom useChart Hook for Data Fetching

Show how to create a custom React Hook, useChart, that encapsulates fetching, loading state, and error handling logic for chart data retrieval.
import React, { useState, useEffect } from 'react';
Import necessary React hooks.
function useChart(dataUrl) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

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

    fetchData();
  }, [dataUrl]);

  return { data, loading, error };
}
Defines the useChart hook, which takes a URL for data fetching, manages loading state, handles potential errors, and finally sets the fetched data.
export default useChart;
Exports the custom useChart hook for use in other components.