import { useEffect, useRef } from "react";
import echarts from "echarts/lib/echarts";
import { EChartsFullOption } from "echarts/lib/option";
import { useDebounce, useSize } from "ahooks";
function useECharts(
chartRef: React.RefObject<HTMLDivElement>,
config: EChartsFullOption
) {
const chartInstance = useRef<echarts.EChartsType | null>(null);
const size = useSize(chartRef);
const debouncedSize = useDebounce(size, { wait: 500 });
useEffect(() => {
function renderChart() {
if (!chartRef.current) {
return;
}
const renderedInstance = echarts.getInstanceByDom(chartRef.current);
if (renderedInstance) {
chartInstance.current = renderedInstance;
} else {
chartInstance.current = echarts.init(chartRef.current);
}
chartInstance.current.setOption(config);
}
renderChart();
}, [chartRef, config]);
useEffect(() => {
return () => {
chartInstance.current?.dispose();
};
}, [chartInstance, debouncedSize]);
return { chartInstance };
}
export default useECharts;