Efficient Data Fetching and Caching with Custom Hook
Showcase a custom hook implementation for fetching chart data from an API, utilizing caching to avoid unnecessary network requests and speed up chart rendering.
import { useState, useEffect } from 'react';Imports necessary hooks from React.
const cache = {};Defines an object to act as a cache for storing fetched data.
const useChartData = (endpoint) => {Declares a custom React hook named useChartData for fetching chart data.
const [data, setData] = useState(null);Initializes state for storing fetched data.
useEffect(() => {Uses the useEffect hook to trigger side effects in the component.
if (cache[endpoint]) {Checks if data for the given endpoint already exists in the cache.
setData(cache[endpoint]);Sets the data from cache if available, avoiding unnecessary fetch.
return;Returns early to skip fetching data from the API.
}Closes the if block.
const fetchData = async () => {Defines an async function to fetch data from the provided endpoint.
const response = await fetch(endpoint);Fetches data asynchronously from the provided endpoint.
const data = await response.json();Parses the fetched data as JSON.
cache[endpoint] = data;Caches the fetched data to avoid future unnecessary requests.
setData(data);Updates the state with the fetched data.
};Closes the async fetchData function.
fetchData();Calls the fetchData function.
}, [endpoint]);Ensures the effect runs when the endpoint changes.
return data;Returns the fetched or cached data from the hook.
};Closes the useChartData custom hook.
export default useChartData;Exports the useChartData hook for reuse in other components.